test(sdk): cover API client, chain, emitter, guards, and segments

This commit is contained in:
DrSmoothl committed 2026-08-14 10:57:16 +08:00
1 parent 80f34ca720
commit 8004e9af9d
6 files changed
+2557

No files matched your search

+698
View File
@@ -0,0 +1,698 @@
import { describe, expect, it } from 'vitest';
import { SnowLumaApiClient, toJsonObject } from '../src/client/api-client';
import {
SnowLumaApiError,
SnowLumaAuthError,
text,
type ActionParams,
type ActionResult,
type ApiResponse,
type RequestOptions,
type SnowLumaAction,
} from '../src';
class RecordingClient extends SnowLumaApiClient {
readonly calls: Array<{
action: string;
params: unknown;
options: RequestOptions | undefined;
}> = [];
response: ApiResponse = { status: 'ok', retcode: 0, data: null };
async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
this.calls.push({ action, params, options });
return this.response as ApiResponse<ActionResult<TAction>>;
}
}
function okClient(data: unknown = null): RecordingClient {
const client = new RecordingClient();
client.response = { status: 'ok', retcode: 0, data };
return client;
}
describe('toJsonObject', () => {
it('returns an empty object for undefined', () => {
expect(toJsonObject(undefined)).toEqual({});
});
it('returns the same object when one is provided', () => {
const value = { domain: 'qun.qq.com' };
expect(toJsonObject(value)).toBe(value);
});
});
describe('SnowLumaApiClient.call', () => {
it('returns response data when status is ok and retcode is 0', async () => {
const client = okClient({ user_id: 1787882683, nickname: 'luma' });
await expect(client.call('get_login_info', {}, { timeoutMs: 1500 })).resolves.toEqual({
user_id: 1787882683,
nickname: 'luma',
});
expect(client.calls).toEqual([
{ action: 'get_login_info', params: {}, options: { timeoutMs: 1500 } },
]);
});
it('throws SnowLumaApiError when status is failed even if retcode is 0', async () => {
const client = new RecordingClient();
const response: ApiResponse = {
status: 'failed',
retcode: 0,
data: null,
wording: 'handler rejected',
};
client.response = response;
await expect(client.call('clean_cache', {})).rejects.toBeInstanceOf(SnowLumaApiError);
await expect(client.call('clean_cache', {})).rejects.toMatchObject({
name: 'SnowLumaApiError',
retcode: 0,
wording: 'handler rejected',
message: 'handler rejected',
response,
});
});
it('throws SnowLumaApiError when retcode is non-zero even if status is ok', async () => {
const client = new RecordingClient();
const response: ApiResponse = { status: 'ok', retcode: 1200, data: null };
client.response = response;
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaApiError);
await expect(client.getStatus()).rejects.toMatchObject({
name: 'SnowLumaApiError',
retcode: 1200,
message: 'SnowLuma API failed with retcode 1200',
response,
});
});
it('throws SnowLumaAuthError for auth retcodes', async () => {
const client = new RecordingClient();
client.response = { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' };
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaAuthError);
client.response = { status: 'ok', retcode: 401, data: null, wording: 'token missing' };
await expect(client.getStatus()).rejects.toMatchObject({
name: 'SnowLumaAuthError',
retcode: 401,
wording: 'token missing',
});
client.response = { status: 'failed', retcode: 403, data: null };
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaAuthError);
});
});
describe('SnowLumaApiClient.raw', () => {
it('unwraps successful data and forwards the raw action arguments', async () => {
const client = okClient({ cookies: 'uin=o10001' });
await expect(client.raw('get_cookies', { domain: 'qun.qq.com' }, { echo: 'raw-1' })).resolves.toEqual({
cookies: 'uin=o10001',
});
expect(client.calls).toEqual([
{ action: 'get_cookies', params: { domain: 'qun.qq.com' }, options: { echo: 'raw-1' } },
]);
});
it('throws on failed envelopes instead of returning them', async () => {
const client = new RecordingClient();
client.response = { status: 'failed', retcode: 1403, data: null, wording: 'denied' };
await expect(client.raw('get_csrf_token', {})).rejects.toBeInstanceOf(SnowLumaApiError);
});
});
describe('SnowLumaApiClient.rawResponse', () => {
it('returns the full envelope without applying call error handling', async () => {
const client = new RecordingClient();
const response: ApiResponse = { status: 'failed', retcode: 1403, data: null, wording: 'denied' };
client.response = response;
await expect(client.rawResponse('get_csrf_token', {}, { echo: 'env-1' })).resolves.toEqual(response);
expect(client.calls).toEqual([
{ action: 'get_csrf_token', params: {}, options: { echo: 'env-1' } },
]);
});
});
describe('SnowLumaApiClient typed actions', () => {
it('maps session helpers to empty-param OneBot actions', async () => {
const client = okClient();
const timeout = { timeoutMs: 2500 };
await client.getLoginInfo();
await client.getStatus(timeout);
await client.getVersionInfo();
await client.canSendImage();
await client.canSendRecord();
await client.getFriendList();
await client.getRKey();
await client.getCsrfToken();
await client.cleanCache();
await client.markAllAsRead();
await client.checkUrlSafely();
await client.getClientKey();
expect(client.calls).toEqual([
{ action: 'get_login_info', params: {}, options: undefined },
{ action: 'get_status', params: {}, options: timeout },
{ action: 'get_version_info', params: {}, options: undefined },
{ action: 'can_send_image', params: {}, options: undefined },
{ action: 'can_send_record', params: {}, options: undefined },
{ action: 'get_friend_list', params: {}, options: undefined },
{ action: 'get_rkey', params: {}, options: undefined },
{ action: 'get_csrf_token', params: {}, options: undefined },
{ action: 'clean_cache', params: {}, options: undefined },
{ action: '_mark_all_as_read', params: {}, options: undefined },
{ action: 'check_url_safely', params: {}, options: undefined },
{ action: 'get_clientkey', params: {}, options: undefined },
]);
});
it('normalizes outgoing messages for send helpers', async () => {
const client = okClient({ message_id: 88 });
await client.sendMsg({
message_type: 'group',
group_id: 941657197,
message: 'plain',
auto_escape: true,
});
await client.sendMsg({
message_type: 'private',
user_id: 10001,
message: { type: 'text', data: { text: 'seg' } },
});
await client.sendPrivateMessage(10002, text('hi'), { autoEscape: true, timeoutMs: 9 });
await client.sendGroupMessage(20002, [{ type: 'text', data: { text: 'arr' } }]);
await client.sendGroupForwardMessage(30003, text('fwd-g'));
await client.sendPrivateForwardMessage(40004, 'fwd-p');
expect(client.calls).toEqual([
{
action: 'send_msg',
params: {
message_type: 'group',
group_id: 941657197,
message: 'plain',
auto_escape: true,
},
options: undefined,
},
{
action: 'send_msg',
params: {
message_type: 'private',
user_id: 10001,
message: [{ type: 'text', data: { text: 'seg' } }],
},
options: undefined,
},
{
action: 'send_private_msg',
params: {
user_id: 10002,
message: [{ type: 'text', data: { text: 'hi' } }],
auto_escape: true,
},
options: { autoEscape: true, timeoutMs: 9 },
},
{
action: 'send_group_msg',
params: {
group_id: 20002,
message: [{ type: 'text', data: { text: 'arr' } }],
auto_escape: undefined,
},
options: undefined,
},
{
action: 'send_group_forward_msg',
params: {
group_id: 30003,
messages: [{ type: 'text', data: { text: 'fwd-g' } }],
},
options: undefined,
},
{
action: 'send_private_forward_msg',
params: {
user_id: 40004,
messages: 'fwd-p',
},
options: undefined,
},
]);
});
it('maps message lookup, delete, and history helpers', async () => {
const client = okClient();
await client.getMessage(71);
await client.deleteMessage(72);
await client.getGroupMessageHistory({ group_id: 941657197, message_id: 73, count: 20, reverse_order: false });
await client.getFriendMessageHistory({ user_id: 10001, count: 8 });
await client.markGroupMessageAsRead(74);
await client.markGroupMessageAsRead(75, 941657198);
await client.markPrivateMessageAsRead(76);
await client.markPrivateMessageAsRead(77, 10002);
await client.markMessageAsRead(78);
await client.markMessageAsRead(79, 10003);
expect(client.calls).toEqual([
{ action: 'get_msg', params: { message_id: 71 }, options: undefined },
{ action: 'delete_msg', params: { message_id: 72 }, options: undefined },
{
action: 'get_group_msg_history',
params: { group_id: 941657197, message_id: 73, count: 20, reverse_order: false },
options: undefined,
},
{
action: 'get_friend_msg_history',
params: { user_id: 10001, count: 8 },
options: undefined,
},
{ action: 'mark_group_msg_as_read', params: { message_id: 74, group_id: undefined }, options: undefined },
{ action: 'mark_group_msg_as_read', params: { message_id: 75, group_id: 941657198 }, options: undefined },
{ action: 'mark_private_msg_as_read', params: { message_id: 76, user_id: undefined }, options: undefined },
{ action: 'mark_private_msg_as_read', params: { message_id: 77, user_id: 10002 }, options: undefined },
{ action: 'mark_msg_as_read', params: { message_id: 78, target_id: undefined }, options: undefined },
{ action: 'mark_msg_as_read', params: { message_id: 79, target_id: 10003 }, options: undefined },
]);
});
it('maps friend and stranger helpers, including optional block', async () => {
const client = okClient();
await client.getStrangerInfo(10011);
await client.deleteFriend(10012);
await client.deleteFriend(10013, { block: true, timeoutMs: 40 });
await client.setFriendRemark(10014, 'alias');
await client.setFriendAddRequest('flag-a');
await client.setFriendAddRequest('flag-b', false);
expect(client.calls).toEqual([
{ action: 'get_stranger_info', params: { user_id: 10011 }, options: undefined },
{ action: 'delete_friend', params: { user_id: 10012, block: undefined }, options: undefined },
{ action: 'delete_friend', params: { user_id: 10013, block: true }, options: { block: true, timeoutMs: 40 } },
{ action: 'set_friend_remark', params: { user_id: 10014, remark: 'alias' }, options: undefined },
{ action: 'set_friend_add_request', params: { flag: 'flag-a', approve: true }, options: undefined },
{ action: 'set_friend_add_request', params: { flag: 'flag-b', approve: false }, options: undefined },
]);
});
it('maps group list and member lookups with noCache', async () => {
const client = okClient();
await client.getGroupList();
await client.getGroupList({ noCache: true, timeoutMs: 11 });
await client.getGroupInfo(941657197);
await client.getGroupInfo(941657198, { noCache: false });
await client.getGroupMemberList(941657199);
await client.getGroupMemberList(941657200, { noCache: true });
await client.getGroupMemberInfo(941657201, 10021);
await client.getGroupMemberInfo(941657202, 10022, { noCache: true });
await client.getGroupInfoEx(941657203);
await client.getGroupInfoEx(941657204, { noCache: true });
await client.getGroupDetailInfo(941657205);
await client.getGroupDetailInfo(941657206, { noCache: true });
expect(client.calls).toEqual([
{ action: 'get_group_list', params: { no_cache: undefined }, options: undefined },
{ action: 'get_group_list', params: { no_cache: true }, options: { noCache: true, timeoutMs: 11 } },
{ action: 'get_group_info', params: { group_id: 941657197, no_cache: undefined }, options: undefined },
{ action: 'get_group_info', params: { group_id: 941657198, no_cache: false }, options: { noCache: false } },
{ action: 'get_group_member_list', params: { group_id: 941657199, no_cache: undefined }, options: undefined },
{ action: 'get_group_member_list', params: { group_id: 941657200, no_cache: true }, options: { noCache: true } },
{
action: 'get_group_member_info',
params: { group_id: 941657201, user_id: 10021, no_cache: undefined },
options: undefined,
},
{
action: 'get_group_member_info',
params: { group_id: 941657202, user_id: 10022, no_cache: true },
options: { noCache: true },
},
{ action: 'get_group_info_ex', params: { group_id: 941657203, no_cache: undefined }, options: undefined },
{ action: 'get_group_info_ex', params: { group_id: 941657204, no_cache: true }, options: { noCache: true } },
{ action: 'get_group_detail_info', params: { group_id: 941657205, no_cache: undefined }, options: undefined },
{ action: 'get_group_detail_info', params: { group_id: 941657206, no_cache: true }, options: { noCache: true } },
]);
});
it('maps honor and system-message helpers', async () => {
const client = okClient();
await client.getGroupHonorInfo({ group_id: 941657210, type: 'talkative' });
await client.getGroupSystemMessages();
await client.getGroupSystemMessages({ groupId: 941657211, onlyPending: true, count: 5 });
expect(client.calls).toEqual([
{ action: 'get_group_honor_info', params: { group_id: 941657210, type: 'talkative' }, options: undefined },
{
action: 'get_group_system_msg',
params: { group_id: undefined, only_pending: undefined, count: undefined },
options: undefined,
},
{
action: 'get_group_system_msg',
params: { group_id: 941657211, only_pending: true, count: 5 },
options: { groupId: 941657211, onlyPending: true, count: 5 },
},
]);
});
it('maps group administration helpers and their defaults', async () => {
const client = okClient();
await client.setGroupKick(941657220, 10031);
await client.setGroupKick(941657221, 10032, { rejectAddRequest: true });
await client.setGroupBan(941657222, 10033);
await client.setGroupBan(941657223, 10034, 600);
await client.setGroupWholeBan(941657224);
await client.setGroupWholeBan(941657225, false);
await client.setGroupAdmin(941657226, 10035);
await client.setGroupAdmin(941657227, 10036, false);
await client.setGroupCard(941657228, 10037);
await client.setGroupCard(941657229, 10038, 'card');
await client.setGroupName(941657230, 'new-name');
await client.setGroupLeave(941657231);
await client.setGroupSpecialTitle(941657232, 10039);
await client.setGroupSpecialTitle(941657233, 10040, 'title');
expect(client.calls).toEqual([
{
action: 'set_group_kick',
params: { group_id: 941657220, user_id: 10031, reject_add_request: undefined },
options: undefined,
},
{
action: 'set_group_kick',
params: { group_id: 941657221, user_id: 10032, reject_add_request: true },
options: { rejectAddRequest: true },
},
{ action: 'set_group_ban', params: { group_id: 941657222, user_id: 10033, duration: undefined }, options: undefined },
{ action: 'set_group_ban', params: { group_id: 941657223, user_id: 10034, duration: 600 }, options: undefined },
{ action: 'set_group_whole_ban', params: { group_id: 941657224, enable: true }, options: undefined },
{ action: 'set_group_whole_ban', params: { group_id: 941657225, enable: false }, options: undefined },
{ action: 'set_group_admin', params: { group_id: 941657226, user_id: 10035, enable: true }, options: undefined },
{ action: 'set_group_admin', params: { group_id: 941657227, user_id: 10036, enable: false }, options: undefined },
{ action: 'set_group_card', params: { group_id: 941657228, user_id: 10037, card: '' }, options: undefined },
{ action: 'set_group_card', params: { group_id: 941657229, user_id: 10038, card: 'card' }, options: undefined },
{ action: 'set_group_name', params: { group_id: 941657230, group_name: 'new-name' }, options: undefined },
{ action: 'set_group_leave', params: { group_id: 941657231 }, options: undefined },
{
action: 'set_group_special_title',
params: { group_id: 941657232, user_id: 10039, special_title: '' },
options: undefined,
},
{
action: 'set_group_special_title',
params: { group_id: 941657233, user_id: 10040, special_title: 'title' },
options: undefined,
},
]);
});
it('maps group and private file helpers', async () => {
const client = okClient();
await client.uploadGroupFile(941657240, '/tmp/a.png');
await client.uploadGroupFile(941657241, '/tmp/b.png', {
name: 'b.png',
folder: '/docs',
folderId: '/abc',
uploadFile: true,
});
await client.uploadPrivateFile(10051, '/tmp/c.png');
await client.uploadPrivateFile(10052, '/tmp/d.png', { name: 'd.png', uploadFile: false });
await client.getGroupFileUrl(941657242, 'file-1');
await client.getGroupFileUrl(941657243, 'file-2', { busid: 102 });
await client.getGroupRootFiles(941657244);
await client.getGroupFilesByFolder(941657245);
await client.getGroupFilesByFolder(941657246, '/sub');
await client.deleteGroupFile(941657247, 'file-3');
await client.moveGroupFile(941657248, 'file-4', '/from', '/to');
await client.createGroupFileFolder(941657249, 'photos');
await client.createGroupFileFolder(941657250, 'docs', '/root');
await client.deleteGroupFileFolder(941657251, '/gone');
await client.renameGroupFileFolder(941657252, '/old', 'new-name');
await client.getPrivateFileUrl(10053, 'file-5', 'hash-5');
await client.getGroupFileSystemInfo(941657253);
expect(client.calls).toEqual([
{
action: 'upload_group_file',
params: {
group_id: 941657240,
file: '/tmp/a.png',
name: undefined,
folder: undefined,
folder_id: undefined,
upload_file: undefined,
},
options: {},
},
{
action: 'upload_group_file',
params: {
group_id: 941657241,
file: '/tmp/b.png',
name: 'b.png',
folder: '/docs',
folder_id: '/abc',
upload_file: true,
},
options: { name: 'b.png', folder: '/docs', folderId: '/abc', uploadFile: true },
},
{
action: 'upload_private_file',
params: { user_id: 10051, file: '/tmp/c.png', name: undefined, upload_file: undefined },
options: {},
},
{
action: 'upload_private_file',
params: { user_id: 10052, file: '/tmp/d.png', name: 'd.png', upload_file: false },
options: { name: 'd.png', uploadFile: false },
},
{ action: 'get_group_file_url', params: { group_id: 941657242, file_id: 'file-1', busid: undefined }, options: undefined },
{ action: 'get_group_file_url', params: { group_id: 941657243, file_id: 'file-2', busid: 102 }, options: { busid: 102 } },
{ action: 'get_group_root_files', params: { group_id: 941657244 }, options: undefined },
{ action: 'get_group_files_by_folder', params: { group_id: 941657245, folder_id: '/' }, options: undefined },
{ action: 'get_group_files_by_folder', params: { group_id: 941657246, folder_id: '/sub' }, options: undefined },
{ action: 'delete_group_file', params: { group_id: 941657247, file_id: 'file-3' }, options: undefined },
{
action: 'move_group_file',
params: {
group_id: 941657248,
file_id: 'file-4',
parent_directory: '/from',
target_directory: '/to',
},
options: undefined,
},
{ action: 'create_group_file_folder', params: { group_id: 941657249, name: 'photos', parent_id: '/' }, options: undefined },
{ action: 'create_group_file_folder', params: { group_id: 941657250, name: 'docs', parent_id: '/root' }, options: undefined },
{ action: 'delete_group_file_folder', params: { group_id: 941657251, folder_id: '/gone' }, options: undefined },
{
action: 'rename_group_file_folder',
params: { group_id: 941657252, folder_id: '/old', new_folder_name: 'new-name' },
options: undefined,
},
{ action: 'get_private_file_url', params: { user_id: 10053, file_id: 'file-5', file_hash: 'hash-5' }, options: undefined },
{ action: 'get_group_file_system_info', params: { group_id: 941657253 }, options: undefined },
]);
});
it('maps group add-request, poke, like, and essence helpers', async () => {
const client = okClient();
await client.setGroupAddRequest('flag-c');
await client.setGroupAddRequest('flag-d', {
subType: 'add',
type: 'group',
approve: false,
reason: 'nope',
});
await client.sendLike(10061);
await client.sendLike(10062, 5);
await client.friendPoke(10063);
await client.friendPoke(10064, { targetId: 10065 });
await client.groupPoke(941657260, 10066);
await client.sendPoke(10067);
await client.sendPoke(10068, { groupId: 941657261 });
await client.setEssenceMessage(81);
await client.deleteEssenceMessage(82);
await client.getEssenceMessageList(941657262);
await client.setGroupReaction({ message_id: 83, code: '76', group_id: 941657263, is_set: true });
expect(client.calls).toEqual([
{
action: 'set_group_add_request',
params: { flag: 'flag-c', sub_type: undefined, type: undefined, approve: undefined, reason: undefined },
options: {},
},
{
action: 'set_group_add_request',
params: { flag: 'flag-d', sub_type: 'add', type: 'group', approve: false, reason: 'nope' },
options: { subType: 'add', type: 'group', approve: false, reason: 'nope' },
},
{ action: 'send_like', params: { user_id: 10061, times: 1 }, options: undefined },
{ action: 'send_like', params: { user_id: 10062, times: 5 }, options: undefined },
{ action: 'friend_poke', params: { user_id: 10063, target_id: undefined }, options: undefined },
{ action: 'friend_poke', params: { user_id: 10064, target_id: 10065 }, options: { targetId: 10065 } },
{ action: 'group_poke', params: { group_id: 941657260, user_id: 10066 }, options: undefined },
{ action: 'send_poke', params: { user_id: 10067, group_id: undefined }, options: undefined },
{ action: 'send_poke', params: { user_id: 10068, group_id: 941657261 }, options: { groupId: 941657261 } },
{ action: 'set_essence_msg', params: { message_id: 81 }, options: undefined },
{ action: 'delete_essence_msg', params: { message_id: 82 }, options: undefined },
{ action: 'get_essence_msg_list', params: { group_id: 941657262 }, options: undefined },
{
action: 'set_group_reaction',
params: { message_id: 83, code: '76', group_id: 941657263, is_set: true },
options: undefined,
},
]);
});
it('maps group-notice helpers to underscored OneBot actions', async () => {
const client = okClient();
await client.sendGroupNotice(941657270, 'welcome');
await client.sendGroupNotice(941657271, 'pinned', {
image: 'https://example.test/n.png',
pinned: 1,
type: 20,
sendToNewMembers: true,
isShowEditCard: 0,
tipWindowType: 1,
confirmRequired: 0,
});
await client.getGroupNotice(941657272);
expect(client.calls).toEqual([
{
action: '_send_group_notice',
params: {
group_id: 941657270,
content: 'welcome',
image: undefined,
pinned: undefined,
type: undefined,
send_to_new_members: undefined,
is_show_edit_card: undefined,
tip_window_type: undefined,
confirm_required: undefined,
},
options: {},
},
{
action: '_send_group_notice',
params: {
group_id: 941657271,
content: 'pinned',
image: 'https://example.test/n.png',
pinned: 1,
type: 20,
send_to_new_members: true,
is_show_edit_card: 0,
tip_window_type: 1,
confirm_required: 0,
},
options: {
image: 'https://example.test/n.png',
pinned: 1,
type: 20,
sendToNewMembers: true,
isShowEditCard: 0,
tipWindowType: 1,
confirmRequired: 0,
},
},
{ action: '_get_group_notice', params: { group_id: 941657272 }, options: undefined },
]);
});
it('forwards forward-message and media helpers without remapping their params', async () => {
const client = okClient();
await client.uploadForwardMessage({ group_id: 941657280, messages: 'up' });
await client.sendForwardMessage({ user_id: 10071, message: 'send' });
await client.getForwardMessage({ id: 'fwd-1' });
await client.getImage({ file: 'img-1' });
await client.getRecord({ file_id: 'rec-1' });
await client.downloadFile({ url: 'https://example.test/a.bin', name: 'a.bin' });
expect(client.calls).toEqual([
{ action: 'upload_forward_msg', params: { group_id: 941657280, messages: 'up' }, options: undefined },
{ action: 'send_forward_msg', params: { user_id: 10071, message: 'send' }, options: undefined },
{ action: 'get_forward_msg', params: { id: 'fwd-1' }, options: undefined },
{ action: 'get_image', params: { file: 'img-1' }, options: undefined },
{ action: 'get_record', params: { file_id: 'rec-1' }, options: undefined },
{ action: 'download_file', params: { url: 'https://example.test/a.bin', name: 'a.bin' }, options: undefined },
]);
});
it('maps cookie, credential, profile, and status helpers', async () => {
const client = okClient();
await client.getCookies();
await client.getCookies({ domain: 'qun.qq.com' });
await client.getCredentials();
await client.getCredentials({ domain: 'qzone.qq.com' });
await client.setQqProfile({ nickname: 'luma', personalNote: 'hello' });
await client.setOnlineStatus(11);
await client.setOnlineStatus(10, { extStatus: 1000, batteryStatus: 80, timeoutMs: 30 });
expect(client.calls).toEqual([
{ action: 'get_cookies', params: {}, options: undefined },
{ action: 'get_cookies', params: { domain: 'qun.qq.com' }, options: undefined },
{ action: 'get_credentials', params: {}, options: undefined },
{ action: 'get_credentials', params: { domain: 'qzone.qq.com' }, options: undefined },
{ action: 'set_qq_profile', params: { nickname: 'luma', personal_note: 'hello' }, options: undefined },
{ action: 'set_online_status', params: { status: 11, ext_status: undefined, battery_status: undefined }, options: {} },
{
action: 'set_online_status',
params: { status: 10, ext_status: 1000, battery_status: 80 },
options: { extStatus: 1000, batteryStatus: 80, timeoutMs: 30 },
},
]);
});
it('maps emoji and system-face helpers including refresh defaults', async () => {
const client = okClient();
await client.setMsgEmojiLike(91, '128076');
await client.setMsgEmojiLike(92, '128077', false);
await client.fetchSysFaces();
await client.fetchSysFaces(true);
await client.fetchFaceEntity(392);
await client.fetchFaceEntity(393, { refresh: true });
await client.searchSysFaces('dragon');
await client.fetchSuperFaceId(394);
await client.fetchSuperFaceId(395, { refresh: false });
expect(client.calls).toEqual([
{ action: 'set_msg_emoji_like', params: { message_id: 91, emoji_id: '128076', set: true }, options: undefined },
{ action: 'set_msg_emoji_like', params: { message_id: 92, emoji_id: '128077', set: false }, options: undefined },
{ action: 'fetch_sys_faces', params: { refresh: false }, options: undefined },
{ action: 'fetch_sys_faces', params: { refresh: true }, options: undefined },
{ action: 'fetch_face_entity', params: { face_id: 392, refresh: false }, options: {} },
{ action: 'fetch_face_entity', params: { face_id: 393, refresh: true }, options: { refresh: true } },
{ action: 'search_sys_faces', params: { query: 'dragon' }, options: undefined },
{ action: 'fetch_super_face_id', params: { face_id: 394, refresh: false }, options: {} },
{ action: 'fetch_super_face_id', params: { face_id: 395, refresh: false }, options: { refresh: false } },
]);
});
});
+506
View File
@@ -0,0 +1,506 @@
import { describe, expect, it, vi } from 'vitest';
import {
at,
atAll,
br,
chain,
contact,
face,
forward,
image,
json,
location,
MessageChain,
music,
node,
normalizeMessage,
poke,
raw,
record,
reply,
share,
text,
video,
xml,
} from '../src';
function sender() {
return {
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 61001 }),
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 61002 }),
};
}
describe('MessageChain.empty and chain()', () => {
it('starts empty', () => {
const empty = MessageChain.empty();
expect(empty).toBeInstanceOf(MessageChain);
expect(empty.length).toBe(0);
expect(empty.isEmpty).toBe(true);
expect(empty.toSegments()).toEqual([]);
expect(chain().toSegments()).toEqual([]);
});
it('updates length and isEmpty after a segment is added', () => {
const next = chain().text('wave');
expect(next.length).toBe(1);
expect(next.isEmpty).toBe(false);
expect(chain().isEmpty).toBe(true);
});
it('does not mutate the previous chain when a segment is added', () => {
const base = text('keep');
const next = base.face(39);
expect(base.toSegments()).toEqual([{ type: 'text', data: { text: 'keep' } }]);
expect(next.toSegments()).toEqual([
{ type: 'text', data: { text: 'keep' } },
{ type: 'face', data: { id: '39' } },
]);
});
});
describe('segment builders', () => {
it('builds a text segment and defaults to an empty string', () => {
expect(text().toSegments()).toEqual([{ type: 'text', data: { text: '' } }]);
expect(text('wave').toSegments()).toEqual([{ type: 'text', data: { text: 'wave' } }]);
expect(chain().text().toSegments()).toEqual([{ type: 'text', data: { text: '' } }]);
});
it('treats br as a newline text segment', () => {
expect(br().toSegments()).toEqual([{ type: 'text', data: { text: '\n' } }]);
});
it('stringifies face ids', () => {
expect(face(39).toSegments()).toEqual([{ type: 'face', data: { id: '39' } }]);
expect(face('178').toSegments()).toEqual([{ type: 'face', data: { id: '178' } }]);
});
it('stringifies at targets and only copies truthy name/uid', () => {
expect(at(31415).toSegments()).toEqual([{ type: 'at', data: { qq: '31415' } }]);
expect(at('all').toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]);
expect(atAll().toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]);
expect(at(31415, { name: 'Ada', uid: 'uid-ada' }).toSegments()).toEqual([
{ type: 'at', data: { qq: '31415', name: 'Ada', uid: 'uid-ada' } },
]);
expect(at(31415, { name: '', uid: '' }).toSegments()).toEqual([
{ type: 'at', data: { qq: '31415' } },
]);
});
it('stringifies reply ids', () => {
expect(reply(88).toSegments()).toEqual([{ type: 'reply', data: { id: '88' } }]);
expect(reply('mid-88').toSegments()).toEqual([{ type: 'reply', data: { id: 'mid-88' } }]);
});
it('spreads image, record, and video options after file', () => {
expect(image('file://pic.webp').toSegments()).toEqual([
{ type: 'image', data: { file: 'file://pic.webp' } },
]);
expect(
image('file://pic.webp', {
type: 'flash',
subType: 4,
summary: 'cover',
url: 'https://cdn.example/pic.webp',
}).toSegments(),
).toEqual([
{
type: 'image',
data: {
file: 'file://pic.webp',
type: 'flash',
subType: 4,
summary: 'cover',
url: 'https://cdn.example/pic.webp',
},
},
]);
expect(record('file://voice.amr').toSegments()).toEqual([
{ type: 'record', data: { file: 'file://voice.amr' } },
]);
expect(record('file://voice.amr', { url: 'https://cdn.example/voice.amr' }).toSegments()).toEqual([
{ type: 'record', data: { file: 'file://voice.amr', url: 'https://cdn.example/voice.amr' } },
]);
expect(video('file://clip.mp4').toSegments()).toEqual([
{ type: 'video', data: { file: 'file://clip.mp4' } },
]);
expect(
video('file://clip.mp4', {
url: 'https://cdn.example/clip.mp4',
thumb: 'file://thumb.jpg',
}).toSegments(),
).toEqual([
{
type: 'video',
data: {
file: 'file://clip.mp4',
url: 'https://cdn.example/clip.mp4',
thumb: 'file://thumb.jpg',
},
},
]);
});
it('keeps a json string and stringifies a json object', () => {
expect(json('{"prompt":"card"}').toSegments()).toEqual([
{ type: 'json', data: { data: '{"prompt":"card"}' } },
]);
expect(json({ prompt: 'card', n: 2 }).toSegments()).toEqual([
{ type: 'json', data: { data: '{"prompt":"card","n":2}' } },
]);
});
it('spreads xml options after the payload', () => {
expect(xml('<item />').toSegments()).toEqual([{ type: 'xml', data: { data: '<item />' } }]);
expect(xml('<item />', { id: 'resid-3' }).toSegments()).toEqual([
{ type: 'xml', data: { data: '<item />', id: 'resid-3' } },
]);
});
it('omits poke id only when it is undefined', () => {
expect(poke(6).toSegments()).toEqual([{ type: 'poke', data: { type: 6 } }]);
expect(poke(6, 0).toSegments()).toEqual([{ type: 'poke', data: { type: 6, id: 0 } }]);
expect(poke('6', '-1').toSegments()).toEqual([{ type: 'poke', data: { type: '6', id: '-1' } }]);
});
it('mirrors a forward id onto res_id and forward_id', () => {
expect(forward('fwd-22').toSegments()).toEqual([
{ type: 'forward', data: { id: 'fwd-22', res_id: 'fwd-22', forward_id: 'fwd-22' } },
]);
});
it('stores node content as given', () => {
const inner = text('nested');
expect(node(20002, 'bot', 'plain').toSegments()).toEqual([
{ type: 'node', data: { user_id: 20002, nickname: 'bot', content: 'plain' } },
]);
expect(node(20002, 'bot', { type: 'text', data: { text: 'seg' } }).toSegments()).toEqual([
{
type: 'node',
data: { user_id: 20002, nickname: 'bot', content: { type: 'text', data: { text: 'seg' } } },
},
]);
expect(node(20002, 'bot', inner).toSegments()).toEqual([
{ type: 'node', data: { user_id: 20002, nickname: 'bot', content: inner } },
]);
});
it('passes share, music, location, and contact data through', () => {
expect(share({ url: 'https://ex.test/page', title: 'Page' }).toSegments()).toEqual([
{ type: 'share', data: { url: 'https://ex.test/page', title: 'Page' } },
]);
expect(
share({
url: 'https://ex.test/page',
title: 'Page',
content: 'blurb',
image: 'https://ex.test/cover.png',
}).toSegments(),
).toEqual([
{
type: 'share',
data: {
url: 'https://ex.test/page',
title: 'Page',
content: 'blurb',
image: 'https://ex.test/cover.png',
},
},
]);
expect(music({ type: 'qq', id: '991' }).toSegments()).toEqual([
{ type: 'music', data: { type: 'qq', id: '991' } },
]);
expect(
location({ lat: 30.1, lon: 120.2, title: 'Hangzhou', content: 'West Lake' }).toSegments(),
).toEqual([
{
type: 'location',
data: { lat: 30.1, lon: 120.2, title: 'Hangzhou', content: 'West Lake' },
},
]);
expect(contact('qq', 20002).toSegments()).toEqual([
{ type: 'contact', data: { type: 'qq', id: 20002 } },
]);
expect(contact('group', '987654').toSegments()).toEqual([
{ type: 'contact', data: { type: 'group', id: '987654' } },
]);
});
it('builds an arbitrary raw segment', () => {
expect(raw('dice', { result: 3 }).toSegments()).toEqual([
{ type: 'dice', data: { result: 3 } },
]);
});
it('chains fluent builders in order', () => {
const built = chain().text('ping').at(20002).br().image('file://b.jpg').face(39);
expect(built.length).toBe(5);
expect(built.toSegments()).toEqual([
{ type: 'text', data: { text: 'ping' } },
{ type: 'at', data: { qq: '20002' } },
{ type: 'text', data: { text: '\n' } },
{ type: 'image', data: { file: 'file://b.jpg' } },
{ type: 'face', data: { id: '39' } },
]);
});
});
describe('append', () => {
it('appends a string as a text segment', () => {
expect(text('pre').append('post').toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'text', data: { text: 'post' } },
]);
expect(text('pre').append('').toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'text', data: { text: '' } },
]);
});
it('returns the same instance when appending an empty array', () => {
const base = text('keep');
expect(base.append([])).toBe(base);
});
it('appends a single segment', () => {
expect(text('pre').append({ type: 'face', data: { id: '39' } }).toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'face', data: { id: '39' } },
]);
});
it('appends a segment array', () => {
expect(
text('pre')
.append([
{ type: 'at', data: { qq: 'all' } },
{ type: 'face', data: { id: '39' } },
])
.toSegments(),
).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'at', data: { qq: 'all' } },
{ type: 'face', data: { id: '39' } },
]);
});
it('appends another chain by copying its segments', () => {
const extra = at(20002).text('!');
expect(text('pre').append(extra).toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'at', data: { qq: '20002' } },
{ type: 'text', data: { text: '!' } },
]);
expect(extra.toSegments()).toEqual([
{ type: 'at', data: { qq: '20002' } },
{ type: 'text', data: { text: '!' } },
]);
});
it('appends a duck-typed chain-like value via toSegments', () => {
const duck = {
length: 1,
toSegments() {
return [{ type: 'poke', data: { type: 6 } }];
},
toJSON() {
return this.toSegments();
},
};
expect(text('pre').append(duck).toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'poke', data: { type: 6 } },
]);
});
});
describe('single-use reply', () => {
it('throws when reply is added twice through reply()', () => {
const once = reply(88);
expect(() => (once as unknown as { reply(id: number): unknown }).reply(89)).toThrow(
'Message segment "reply" can only appear once in a chain',
);
});
it('throws when a second reply is appended', () => {
expect(() => reply(88).append({ type: 'reply', data: { id: '89' } })).toThrow(
'Message segment "reply" can only appear once in a chain',
);
expect(() =>
chain().append([
{ type: 'reply', data: { id: '88' } },
{ type: 'text', data: { text: 'x' } },
{ type: 'reply', data: { id: '89' } },
]),
).toThrow('Message segment "reply" can only appear once in a chain');
});
it('throws when raw reply is added twice', () => {
expect(() => raw('reply', { id: '88' }).raw('reply', { id: '89' })).toThrow(
'Message segment "reply" can only appear once in a chain',
);
});
it('allows two independent chains to each have their own reply', () => {
const base = text('fork');
expect(base.reply(88).toSegments()).toEqual([
{ type: 'text', data: { text: 'fork' } },
{ type: 'reply', data: { id: '88' } },
]);
expect(base.reply(89).toSegments()).toEqual([
{ type: 'text', data: { text: 'fork' } },
{ type: 'reply', data: { id: '89' } },
]);
});
it('allows non-reply types, including raw, to appear more than once', () => {
expect(image('a.webp').image('b.webp').toSegments()).toEqual([
{ type: 'image', data: { file: 'a.webp' } },
{ type: 'image', data: { file: 'b.webp' } },
]);
expect(raw('dice', { result: 1 }).raw('dice', { result: 2 }).toSegments()).toEqual([
{ type: 'dice', data: { result: 1 } },
{ type: 'dice', data: { result: 2 } },
]);
});
it('still allows other segments after a reply', () => {
expect(reply(88).text('after').toSegments()).toEqual([
{ type: 'reply', data: { id: '88' } },
{ type: 'text', data: { text: 'after' } },
]);
});
});
describe('serialization and iteration', () => {
it('returns a shallow copy from build, toArray, toSegments, and toJSON', () => {
const built = text('copy').at(20002);
const viaBuild = built.build();
const viaArray = built.toArray();
const viaSegments = built.toSegments();
const viaJson = built.toJSON();
const expected = [
{ type: 'text', data: { text: 'copy' } },
{ type: 'at', data: { qq: '20002' } },
];
expect(viaBuild).toEqual(expected);
expect(viaArray).toEqual(expected);
expect(viaSegments).toEqual(expected);
expect(viaJson).toEqual(expected);
expect(viaBuild).not.toBe(viaArray);
expect(viaArray).not.toBe(viaSegments);
expect(viaSegments).not.toBe(viaJson);
viaBuild.push({ type: 'face', data: { id: '1' } });
expect(built.toSegments()).toEqual(expected);
expect(built.length).toBe(2);
});
it('uses toJSON when stringified', () => {
expect(JSON.parse(JSON.stringify(text('copy').at(20002)))).toEqual([
{ type: 'text', data: { text: 'copy' } },
{ type: 'at', data: { qq: '20002' } },
]);
});
it('renders CQ text through toString', () => {
expect(chain().toString()).toBe('');
expect(text('A&B[C]').toString()).toBe('A&amp;B&#91;C&#93;');
expect(text('wave').at(20002).face(39).toString()).toBe('wave[CQ:at,qq=20002][CQ:face,id=39]');
expect(image('a,b').toString()).toBe('[CQ:image,file=a&#44;b]');
expect(raw('dice', {}).toString()).toBe('[CQ:dice]');
expect(chain().append({ type: 'image', data: { file: 'z.webp', url: undefined } }).toString()).toBe(
'[CQ:image,file=z.webp]',
);
});
it('iterates stored segments', () => {
const built = text('wave').face(39);
expect([...built]).toEqual([
{ type: 'text', data: { text: 'wave' } },
{ type: 'face', data: { id: '39' } },
]);
const walked: unknown[] = [];
for (const segment of built) {
walked.push(segment);
}
expect(walked).toEqual([
{ type: 'text', data: { text: 'wave' } },
{ type: 'face', data: { id: '39' } },
]);
});
});
describe('sendToGroup and sendToPrivate', () => {
it('forwards the chain instance and options to the client', async () => {
const client = sender();
const groupPayload = text('group-hi');
const privatePayload = text('priv-hi');
const options = { autoEscape: true, timeoutMs: 2500, echo: 'echo-chain' };
await expect(groupPayload.sendToGroup(client, 70001, options)).resolves.toEqual({
message_id: 61001,
});
await expect(privatePayload.sendToPrivate(client, 80001, options)).resolves.toEqual({
message_id: 61002,
});
expect(client.sendGroupMessage).toHaveBeenCalledTimes(1);
expect(client.sendGroupMessage).toHaveBeenCalledWith(70001, groupPayload, options);
expect(client.sendPrivateMessage).toHaveBeenCalledTimes(1);
expect(client.sendPrivateMessage).toHaveBeenCalledWith(80001, privatePayload, options);
});
it('passes undefined options when none are given', async () => {
const client = sender();
const payload = text('plain');
await payload.sendToGroup(client, 70002);
await payload.sendToPrivate(client, 80002);
expect(client.sendGroupMessage).toHaveBeenCalledWith(70002, payload, undefined);
expect(client.sendPrivateMessage).toHaveBeenCalledWith(80002, payload, undefined);
});
});
describe('normalizeMessage', () => {
it('returns a string unchanged', () => {
expect(normalizeMessage('plain-text')).toBe('plain-text');
expect(normalizeMessage('')).toBe('');
});
it('returns toSegments() for a chain and for duck-typed chain-like values', () => {
expect(normalizeMessage(text('wave').at(20002))).toEqual([
{ type: 'text', data: { text: 'wave' } },
{ type: 'at', data: { qq: '20002' } },
]);
const segs = [{ type: 'face', data: { id: '39' } }];
const duck = { toSegments: () => segs };
expect(normalizeMessage(duck)).toBe(segs);
});
it('returns an array input by reference', () => {
const segs = [{ type: 'text', data: { text: 'arr' } }];
expect(normalizeMessage(segs)).toBe(segs);
});
it('wraps a single segment in a new array', () => {
const segment = { type: 'text', data: { text: 'solo' } };
expect(normalizeMessage(segment)).toEqual([segment]);
expect(normalizeMessage(segment)).not.toBe(segment);
});
it('does not treat an object with a non-function toSegments as a chain', () => {
const value = { type: 'text', data: { text: 'solo' }, toSegments: 0 };
expect(normalizeMessage(value as never)).toEqual([value]);
});
});
+331
View File
@@ -0,0 +1,331 @@
import { describe, expect, it } from 'vitest';
import { Emitter } from '../src/emitter';
type TestEvents = {
open: undefined;
data: string;
count: number;
close: { code: number; reason: string };
};
describe('Emitter', () => {
it('delivers a payload to a listener registered with on', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.on('data', (payload) => {
seen.push(payload);
});
emitter.emit('data', 'hello');
expect(seen).toEqual(['hello']);
});
it('invokes every listener for the same event in registration order', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.on('data', (payload) => {
seen.push(`first:${payload}`);
});
emitter.on('data', (payload) => {
seen.push(`second:${payload}`);
});
emitter.emit('data', 'alpha');
expect(seen).toEqual(['first:alpha', 'second:alpha']);
});
it('keeps listeners for different events isolated', () => {
const emitter = new Emitter<TestEvents>();
const data: string[] = [];
const counts: number[] = [];
emitter.on('data', (payload) => {
data.push(payload);
});
emitter.on('count', (payload) => {
counts.push(payload);
});
emitter.emit('data', 'alpha');
emitter.emit('count', 7);
emitter.emit('data', 'beta');
expect(data).toEqual(['alpha', 'beta']);
expect(counts).toEqual([7]);
});
it('passes the payload object through by reference', () => {
const emitter = new Emitter<TestEvents>();
const payload = { code: 1000, reason: 'done' };
const seen: Array<{ code: number; reason: string }> = [];
emitter.on('close', (value) => {
seen.push(value);
});
emitter.emit('close', payload);
expect(seen).toEqual([{ code: 1000, reason: 'done' }]);
expect(seen[0]).toBe(payload);
});
it('forwards an undefined payload for events typed as undefined', () => {
const emitter = new Emitter<TestEvents>();
const seen: Array<undefined> = [];
emitter.on('open', (payload) => {
seen.push(payload);
});
emitter.emit('open', undefined);
expect(seen).toEqual([undefined]);
});
it('stores a listener only once when the same function is registered twice', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const listener = (payload: string) => {
seen.push(payload);
};
emitter.on('data', listener);
emitter.on('data', listener);
emitter.emit('data', 'once-only');
expect(seen).toEqual(['once-only']);
});
it('returns an unsubscribe function from on that stops later delivery', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.on('data', (payload) => {
seen.push(payload);
});
off();
emitter.emit('data', 'nope');
expect(seen).toEqual([]);
});
it('does not throw when emit is called with no listeners for that event', () => {
const emitter = new Emitter<TestEvents>();
expect(() => emitter.emit('data', 'orphan')).not.toThrow();
});
it('does not deliver after every listener has been unsubscribed, even if the event key remains', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.on('data', (payload) => {
seen.push(payload);
});
off();
emitter.emit('data', 'ghost');
expect(seen).toEqual([]);
});
it('fires a once listener exactly once', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.once('data', (payload) => {
seen.push(payload);
});
emitter.emit('data', 'first');
emitter.emit('data', 'second');
expect(seen).toEqual(['first']);
});
it('lets once and on listeners share an event without once firing again', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.on('data', (payload) => {
seen.push(`on:${payload}`);
});
emitter.once('data', (payload) => {
seen.push(`once:${payload}`);
});
emitter.emit('data', 'a');
emitter.emit('data', 'b');
expect(seen).toEqual(['on:a', 'once:a', 'on:b']);
});
it('does not call a once listener that was unsubscribed before emit', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.once('data', (payload) => {
seen.push(payload);
});
off();
emitter.emit('data', 'nope');
expect(seen).toEqual([]);
});
it('allows calling the once unsubscribe after it has already fired', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.once('data', (payload) => {
seen.push(payload);
});
emitter.emit('data', 'first');
off();
emitter.emit('data', 'second');
expect(seen).toEqual(['first']);
});
it('does not re-enter a once listener that emits the same event again', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.once('data', (payload) => {
seen.push(payload);
emitter.emit('data', 'again');
});
emitter.emit('data', 'first');
expect(seen).toEqual(['first']);
});
it('does not cancel a once subscription when off is given the original listener', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const listener = (payload: string) => {
seen.push(payload);
};
emitter.once('data', listener);
emitter.off('data', listener);
emitter.emit('data', 'still');
expect(seen).toEqual(['still']);
});
it('removes only the given listener when off is called', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const keep = (payload: string) => {
seen.push(`keep:${payload}`);
};
const drop = (payload: string) => {
seen.push(`drop:${payload}`);
};
emitter.on('data', keep);
emitter.on('data', drop);
emitter.off('data', drop);
emitter.emit('data', 'x');
expect(seen).toEqual(['keep:x']);
});
it('does not throw when off is called for an event that was never registered', () => {
const emitter = new Emitter<TestEvents>();
expect(() => {
emitter.off('data', () => {});
}).not.toThrow();
});
it('does not throw when off is called with a listener that was never added', () => {
const emitter = new Emitter<TestEvents>();
emitter.on('data', (payload) => {
void payload;
});
expect(() => {
emitter.off('data', () => {});
}).not.toThrow();
});
it('still delivers to a listener removed by an earlier listener during the same emit', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const second = (payload: string) => {
seen.push(`second:${payload}`);
};
emitter.on('data', (payload) => {
seen.push(`first:${payload}`);
emitter.off('data', second);
});
emitter.on('data', second);
emitter.emit('data', 'keep');
expect(seen).toEqual(['first:keep', 'second:keep']);
});
it('does not deliver to a listener added during the same emit', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const late = (payload: string) => {
seen.push(`late:${payload}`);
};
emitter.on('data', (payload) => {
seen.push(`early:${payload}`);
emitter.on('data', late);
});
emitter.emit('data', 'now');
emitter.emit('data', 'next');
expect(seen).toEqual(['early:now', 'early:next', 'late:next']);
});
it('stops all listeners after clear', () => {
const emitter = new Emitter<TestEvents>();
const seen: Array<string | number> = [];
emitter.on('data', (payload) => {
seen.push(payload);
});
emitter.on('count', (payload) => {
seen.push(payload);
});
emitter.clear();
emitter.emit('data', 'x');
emitter.emit('count', 1);
expect(seen).toEqual([]);
});
it('accepts new listeners after clear', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.on('data', (payload) => {
seen.push(`old:${payload}`);
});
emitter.clear();
emitter.on('data', (payload) => {
seen.push(`new:${payload}`);
});
emitter.emit('data', 'after');
expect(seen).toEqual(['new:after']);
});
it('does not throw when off is called after clear', () => {
const emitter = new Emitter<TestEvents>();
const listener = (payload: string) => {
void payload;
};
emitter.on('data', listener);
emitter.clear();
expect(() => {
emitter.off('data', listener);
}).not.toThrow();
});
});
+450
View File
@@ -0,0 +1,450 @@
import { describe, expect, it } from 'vitest';
import {
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
noticeType,
requestType,
type OneBotGroupMessageEvent,
type OneBotMetaEvent,
type OneBotNoticeEvent,
type OneBotPrivateMessageEvent,
type OneBotRequestEvent,
type SnowLumaEvent,
} from '../src';
const PRIVATE_MESSAGE: OneBotPrivateMessageEvent = {
time: 1_700_000_001,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 11,
message_seq: 12,
user_id: 20001,
message: [{ type: 'text', data: { text: 'hi' } }],
raw_message: 'hi',
font: 0,
sender: { user_id: 20001, nickname: 'alice' },
};
const PRIVATE_SENT: OneBotPrivateMessageEvent = {
time: 1_700_000_002,
self_id: 10000,
post_type: 'message_sent',
message_type: 'private',
sub_type: 'friend',
message_id: 13,
user_id: 20002,
message: 'echo',
raw_message: 'echo',
font: 0,
sender: { user_id: 10000, nickname: 'bot' },
};
const GROUP_MESSAGE: OneBotGroupMessageEvent = {
time: 1_700_000_003,
self_id: 10000,
post_type: 'message',
message_type: 'group',
sub_type: 'normal',
message_id: 21,
message_seq: 22,
group_id: 30001,
user_id: 20003,
message: [{ type: 'text', data: { text: 'hey' } }],
raw_message: 'hey',
font: 0,
sender: { user_id: 20003, nickname: 'bob', card: 'Bobby', role: 'member' },
};
const GROUP_SENT: OneBotGroupMessageEvent = {
time: 1_700_000_004,
self_id: 10000,
post_type: 'message_sent',
message_type: 'group',
sub_type: 'normal',
message_id: 23,
group_id: 30002,
user_id: 10000,
message: 'sent',
raw_message: 'sent',
font: 0,
sender: { user_id: 10000, nickname: 'bot' },
};
const NOTICE: OneBotNoticeEvent = {
time: 1_700_000_005,
self_id: 10000,
post_type: 'notice',
notice_type: 'group_increase',
};
const REQUEST: OneBotRequestEvent = {
time: 1_700_000_006,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
flag: 'flag-friend-1',
user_id: 20004,
comment: 'please',
};
const META: OneBotMetaEvent = {
time: 1_700_000_007,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: 'heartbeat',
};
const UNKNOWN: SnowLumaEvent = {
time: 1_700_000_008,
self_id: 10000,
post_type: 'unknown',
};
describe('isMessageEvent', () => {
it('accepts inbound private and group messages', () => {
expect(isMessageEvent(PRIVATE_MESSAGE)).toBe(true);
expect(isMessageEvent(GROUP_MESSAGE)).toBe(true);
});
it('accepts message_sent private and group events', () => {
expect(isMessageEvent(PRIVATE_SENT)).toBe(true);
expect(isMessageEvent(GROUP_SENT)).toBe(true);
});
it('rejects message post types whose message_type is not private or group', () => {
const guild: SnowLumaEvent = {
time: 9,
self_id: 10000,
post_type: 'message',
message_type: 'guild',
};
const sentChannel: SnowLumaEvent = {
time: 10,
self_id: 10000,
post_type: 'message_sent',
message_type: 'channel',
};
const missingType: SnowLumaEvent = {
time: 11,
self_id: 10000,
post_type: 'message',
};
expect(isMessageEvent(guild)).toBe(false);
expect(isMessageEvent(sentChannel)).toBe(false);
expect(isMessageEvent(missingType)).toBe(false);
});
it('rejects non-message events even when message_type is present', () => {
const noticeShaped: SnowLumaEvent = {
time: 12,
self_id: 10000,
post_type: 'notice',
notice_type: 'notify',
message_type: 'private',
};
expect(isMessageEvent(NOTICE)).toBe(false);
expect(isMessageEvent(REQUEST)).toBe(false);
expect(isMessageEvent(META)).toBe(false);
expect(isMessageEvent(UNKNOWN)).toBe(false);
expect(isMessageEvent(noticeShaped)).toBe(false);
});
});
describe('isPrivateMessageEvent', () => {
it('accepts private inbound and sent messages', () => {
expect(isPrivateMessageEvent(PRIVATE_MESSAGE)).toBe(true);
expect(isPrivateMessageEvent(PRIVATE_SENT)).toBe(true);
});
it('rejects group messages and non-message events', () => {
expect(isPrivateMessageEvent(GROUP_MESSAGE)).toBe(false);
expect(isPrivateMessageEvent(GROUP_SENT)).toBe(false);
expect(isPrivateMessageEvent(NOTICE)).toBe(false);
expect(isPrivateMessageEvent(REQUEST)).toBe(false);
expect(isPrivateMessageEvent(META)).toBe(false);
});
it('rejects private message_type when post_type is not a message kind', () => {
const leftover: SnowLumaEvent = {
time: 13,
self_id: 10000,
post_type: 'notice',
notice_type: 'friend_add',
message_type: 'private',
};
expect(isPrivateMessageEvent(leftover)).toBe(false);
});
});
describe('isGroupMessageEvent', () => {
it('accepts group inbound and sent messages', () => {
expect(isGroupMessageEvent(GROUP_MESSAGE)).toBe(true);
expect(isGroupMessageEvent(GROUP_SENT)).toBe(true);
});
it('rejects private messages and non-message events', () => {
expect(isGroupMessageEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isGroupMessageEvent(PRIVATE_SENT)).toBe(false);
expect(isGroupMessageEvent(NOTICE)).toBe(false);
expect(isGroupMessageEvent(REQUEST)).toBe(false);
expect(isGroupMessageEvent(META)).toBe(false);
});
it('rejects group message_type when post_type is not a message kind', () => {
const leftover: SnowLumaEvent = {
time: 14,
self_id: 10000,
post_type: 'request',
request_type: 'group',
flag: 'flag-x',
message_type: 'group',
};
expect(isGroupMessageEvent(leftover)).toBe(false);
});
});
describe('isNoticeEvent', () => {
it('accepts notice events with a string notice_type', () => {
expect(isNoticeEvent(NOTICE)).toBe(true);
expect(isNoticeEvent({
time: 15,
self_id: 10000,
post_type: 'notice',
notice_type: '',
})).toBe(true);
});
it('rejects notice post_type when notice_type is not a string', () => {
const missing: SnowLumaEvent = {
time: 16,
self_id: 10000,
post_type: 'notice',
};
const numeric: SnowLumaEvent = {
time: 17,
self_id: 10000,
post_type: 'notice',
notice_type: 7,
};
const nulled: SnowLumaEvent = {
time: 18,
self_id: 10000,
post_type: 'notice',
notice_type: null,
};
expect(isNoticeEvent(missing)).toBe(false);
expect(isNoticeEvent(numeric)).toBe(false);
expect(isNoticeEvent(nulled)).toBe(false);
});
it('rejects other post types', () => {
expect(isNoticeEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isNoticeEvent(REQUEST)).toBe(false);
expect(isNoticeEvent(META)).toBe(false);
expect(isNoticeEvent(UNKNOWN)).toBe(false);
});
});
describe('isRequestEvent', () => {
it('accepts request events with string request_type and flag', () => {
expect(isRequestEvent(REQUEST)).toBe(true);
expect(isRequestEvent({
time: 19,
self_id: 10000,
post_type: 'request',
request_type: 'group',
sub_type: 'add',
flag: '',
group_id: 30003,
})).toBe(true);
});
it('rejects request post_type when request_type or flag is not a string', () => {
const missingFlag: SnowLumaEvent = {
time: 20,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
};
const numericFlag: SnowLumaEvent = {
time: 21,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
flag: 99,
};
const missingType: SnowLumaEvent = {
time: 22,
self_id: 10000,
post_type: 'request',
flag: 'flag-2',
};
const numericType: SnowLumaEvent = {
time: 23,
self_id: 10000,
post_type: 'request',
request_type: 1,
flag: 'flag-3',
};
const nullFlag: SnowLumaEvent = {
time: 24,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
flag: null,
};
expect(isRequestEvent(missingFlag)).toBe(false);
expect(isRequestEvent(numericFlag)).toBe(false);
expect(isRequestEvent(missingType)).toBe(false);
expect(isRequestEvent(numericType)).toBe(false);
expect(isRequestEvent(nullFlag)).toBe(false);
});
it('rejects other post types even when request fields are present', () => {
const leftover: SnowLumaEvent = {
time: 25,
self_id: 10000,
post_type: 'notice',
notice_type: 'group_ban',
request_type: 'group',
flag: 'flag-4',
};
expect(isRequestEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isRequestEvent(NOTICE)).toBe(false);
expect(isRequestEvent(META)).toBe(false);
expect(isRequestEvent(leftover)).toBe(false);
});
});
describe('isMetaEvent', () => {
it('accepts meta_event events with a string meta_event_type', () => {
expect(isMetaEvent(META)).toBe(true);
expect(isMetaEvent({
time: 26,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: 'lifecycle',
})).toBe(true);
});
it('rejects meta_event post_type when meta_event_type is not a string', () => {
const missing: SnowLumaEvent = {
time: 27,
self_id: 10000,
post_type: 'meta_event',
};
const numeric: SnowLumaEvent = {
time: 28,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: 0,
};
const nulled: SnowLumaEvent = {
time: 29,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: null,
};
expect(isMetaEvent(missing)).toBe(false);
expect(isMetaEvent(numeric)).toBe(false);
expect(isMetaEvent(nulled)).toBe(false);
});
it('rejects other post types', () => {
expect(isMetaEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isMetaEvent(NOTICE)).toBe(false);
expect(isMetaEvent(REQUEST)).toBe(false);
expect(isMetaEvent(UNKNOWN)).toBe(false);
});
});
describe('noticeType', () => {
it('matches notice events by notice_type', () => {
const isIncrease = noticeType('group_increase');
const isDecrease = noticeType('group_decrease');
expect(isIncrease(NOTICE)).toBe(true);
expect(isDecrease(NOTICE)).toBe(false);
expect(isIncrease({
time: 30,
self_id: 10000,
post_type: 'notice',
notice_type: 'group_decrease',
})).toBe(false);
});
it('rejects events that fail isNoticeEvent', () => {
const isIncrease = noticeType('group_increase');
const missingType: SnowLumaEvent = {
time: 31,
self_id: 10000,
post_type: 'notice',
};
const leftover: SnowLumaEvent = {
time: 32,
self_id: 10000,
post_type: 'message',
message_type: 'private',
notice_type: 'group_increase',
};
expect(isIncrease(missingType)).toBe(false);
expect(isIncrease(leftover)).toBe(false);
expect(isIncrease(REQUEST)).toBe(false);
expect(isIncrease(PRIVATE_MESSAGE)).toBe(false);
});
});
describe('requestType', () => {
it('matches request events by request_type', () => {
const isFriend = requestType('friend');
const isGroup = requestType('group');
expect(isFriend(REQUEST)).toBe(true);
expect(isGroup(REQUEST)).toBe(false);
expect(isFriend({
time: 33,
self_id: 10000,
post_type: 'request',
request_type: 'group',
flag: 'flag-group-1',
})).toBe(false);
});
it('rejects events that fail isRequestEvent', () => {
const isFriend = requestType('friend');
const missingFlag: SnowLumaEvent = {
time: 34,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
};
const leftover: SnowLumaEvent = {
time: 35,
self_id: 10000,
post_type: 'notice',
notice_type: 'friend_add',
request_type: 'friend',
flag: 'flag-5',
};
expect(isFriend(missingFlag)).toBe(false);
expect(isFriend(leftover)).toBe(false);
expect(isFriend(NOTICE)).toBe(false);
expect(isFriend(META)).toBe(false);
});
});
+347
View File
@@ -0,0 +1,347 @@
import { describe, expect, it } from 'vitest';
import { segments } from '../src/messages/segments';
describe('segments.text', () => {
it('wraps a string as a text segment', () => {
expect(segments.text('hello')).toEqual({ type: 'text', data: { text: 'hello' } });
});
it('keeps empty text', () => {
expect(segments.text('')).toEqual({ type: 'text', data: { text: '' } });
});
});
describe('segments.face', () => {
it('stringifies a numeric face id', () => {
expect(segments.face(14)).toEqual({ type: 'face', data: { id: '14' } });
});
it('keeps a string face id', () => {
expect(segments.face('178')).toEqual({ type: 'face', data: { id: '178' } });
});
it('stringifies zero', () => {
expect(segments.face(0)).toEqual({ type: 'face', data: { id: '0' } });
});
});
describe('segments.at', () => {
it('stringifies a numeric qq and omits empty options', () => {
expect(segments.at(10001)).toEqual({ type: 'at', data: { qq: '10001' } });
});
it('supports at-all', () => {
expect(segments.at('all')).toEqual({ type: 'at', data: { qq: 'all' } });
});
it('includes name when provided', () => {
expect(segments.at(10001, { name: 'luma' })).toEqual({
type: 'at',
data: { qq: '10001', name: 'luma' },
});
});
it('includes uid when provided', () => {
expect(segments.at(10001, { uid: 'u_abc' })).toEqual({
type: 'at',
data: { qq: '10001', uid: 'u_abc' },
});
});
it('includes both name and uid', () => {
expect(segments.at(10001, { name: 'luma', uid: 'u_abc' })).toEqual({
type: 'at',
data: { qq: '10001', name: 'luma', uid: 'u_abc' },
});
});
it('omits empty name and uid', () => {
expect(segments.at(10001, { name: '', uid: '' })).toEqual({
type: 'at',
data: { qq: '10001' },
});
});
});
describe('segments.reply', () => {
it('stringifies a numeric message id', () => {
expect(segments.reply(7)).toEqual({ type: 'reply', data: { id: '7' } });
});
it('keeps a string message id', () => {
expect(segments.reply('abc')).toEqual({ type: 'reply', data: { id: 'abc' } });
});
});
describe('segments.image', () => {
it('uses only the file when no options are given', () => {
expect(segments.image('/tmp/a.png')).toEqual({
type: 'image',
data: { file: '/tmp/a.png' },
});
});
it('spreads image options after file', () => {
expect(
segments.image('base64://abc', {
type: 'flash',
subType: 1,
summary: 'pic',
url: 'https://example.com/a.png',
}),
).toEqual({
type: 'image',
data: {
file: 'base64://abc',
type: 'flash',
subType: 1,
summary: 'pic',
url: 'https://example.com/a.png',
},
});
});
});
describe('segments.record', () => {
it('uses only the file when no options are given', () => {
expect(segments.record('/tmp/a.amr')).toEqual({
type: 'record',
data: { file: '/tmp/a.amr' },
});
});
it('spreads record options after file', () => {
expect(segments.record('/tmp/a.amr', { url: 'https://example.com/a.amr' })).toEqual({
type: 'record',
data: { file: '/tmp/a.amr', url: 'https://example.com/a.amr' },
});
});
});
describe('segments.video', () => {
it('uses only the file when no options are given', () => {
expect(segments.video('/tmp/a.mp4')).toEqual({
type: 'video',
data: { file: '/tmp/a.mp4' },
});
});
it('spreads video options after file', () => {
expect(
segments.video('/tmp/a.mp4', {
url: 'https://example.com/a.mp4',
thumb: '/tmp/thumb.jpg',
}),
).toEqual({
type: 'video',
data: {
file: '/tmp/a.mp4',
url: 'https://example.com/a.mp4',
thumb: '/tmp/thumb.jpg',
},
});
});
});
describe('segments.json', () => {
it('keeps a JSON string as-is', () => {
expect(segments.json('{"app":"com.tencent.miniapp"}')).toEqual({
type: 'json',
data: { data: '{"app":"com.tencent.miniapp"}' },
});
});
it('stringifies a JSON object', () => {
expect(segments.json({ app: 'com.tencent.miniapp', desc: 'hi' })).toEqual({
type: 'json',
data: { data: '{"app":"com.tencent.miniapp","desc":"hi"}' },
});
});
});
describe('segments.xml', () => {
it('uses only the xml payload when no options are given', () => {
expect(segments.xml('<msg />')).toEqual({
type: 'xml',
data: { data: '<msg />' },
});
});
it('spreads xml options after data', () => {
expect(segments.xml('<msg />', { id: '12345' })).toEqual({
type: 'xml',
data: { data: '<msg />', id: '12345' },
});
});
});
describe('segments.poke', () => {
it('omits id when it is not provided', () => {
expect(segments.poke(1)).toEqual({ type: 'poke', data: { type: 1 } });
});
it('includes a numeric id', () => {
expect(segments.poke(1, -1)).toEqual({ type: 'poke', data: { type: 1, id: -1 } });
});
it('keeps string type and id', () => {
expect(segments.poke('1', '0')).toEqual({ type: 'poke', data: { type: '1', id: '0' } });
});
it('includes an id of 0', () => {
expect(segments.poke(1, 0)).toEqual({ type: 'poke', data: { type: 1, id: 0 } });
});
});
describe('segments.forward', () => {
it('mirrors the id onto res_id and forward_id', () => {
expect(segments.forward('res-9')).toEqual({
type: 'forward',
data: { id: 'res-9', res_id: 'res-9', forward_id: 'res-9' },
});
});
});
describe('segments.node', () => {
it('stores user_id, nickname, and string content', () => {
expect(segments.node(10001, 'luma', 'hello')).toEqual({
type: 'node',
data: { user_id: 10001, nickname: 'luma', content: 'hello' },
});
});
it('stores a single segment as content', () => {
expect(segments.node(10001, 'luma', { type: 'text', data: { text: 'hi' } })).toEqual({
type: 'node',
data: {
user_id: 10001,
nickname: 'luma',
content: { type: 'text', data: { text: 'hi' } },
},
});
});
it('stores a segment array as content', () => {
expect(segments.node(10001, 'luma', [{ type: 'text', data: { text: 'hi' } }])).toEqual({
type: 'node',
data: {
user_id: 10001,
nickname: 'luma',
content: [{ type: 'text', data: { text: 'hi' } }],
},
});
});
});
describe('segments.share', () => {
it('passes required share fields through', () => {
expect(segments.share({ url: 'https://example.com', title: 'Example' })).toEqual({
type: 'share',
data: { url: 'https://example.com', title: 'Example' },
});
});
it('passes optional share fields through', () => {
expect(
segments.share({
url: 'https://example.com',
title: 'Example',
content: 'desc',
image: 'https://example.com/a.png',
}),
).toEqual({
type: 'share',
data: {
url: 'https://example.com',
title: 'Example',
content: 'desc',
image: 'https://example.com/a.png',
},
});
});
});
describe('segments.music', () => {
it('passes platform music id data through', () => {
expect(segments.music({ type: '163', id: '12345' })).toEqual({
type: 'music',
data: { type: '163', id: '12345' },
});
});
it('passes custom music data through', () => {
expect(
segments.music({
type: 'custom',
url: 'https://example.com/song',
audio: 'https://example.com/song.mp3',
title: 'Song',
image: 'https://example.com/cover.jpg',
content: 'Artist',
}),
).toEqual({
type: 'music',
data: {
type: 'custom',
url: 'https://example.com/song',
audio: 'https://example.com/song.mp3',
title: 'Song',
image: 'https://example.com/cover.jpg',
content: 'Artist',
},
});
});
});
describe('segments.location', () => {
it('passes numeric coordinates and labels through', () => {
expect(
segments.location({
lat: 39.9,
lon: 116.4,
title: 'Beijing',
content: 'Tiananmen',
}),
).toEqual({
type: 'location',
data: {
lat: 39.9,
lon: 116.4,
title: 'Beijing',
content: 'Tiananmen',
},
});
});
it('passes string coordinates through', () => {
expect(segments.location({ lat: '31.2', lon: '121.5' })).toEqual({
type: 'location',
data: { lat: '31.2', lon: '121.5' },
});
});
});
describe('segments.contact', () => {
it('builds a qq contact with a numeric id', () => {
expect(segments.contact('qq', 10001)).toEqual({
type: 'contact',
data: { type: 'qq', id: 10001 },
});
});
it('builds a group contact with a string id', () => {
expect(segments.contact('group', '123456')).toEqual({
type: 'contact',
data: { type: 'group', id: '123456' },
});
});
});
describe('segments.raw', () => {
it('builds an arbitrary typed segment', () => {
expect(segments.raw('dice', { result: 6 })).toEqual({
type: 'dice',
data: { result: 6 },
});
});
});
+225
View File
@@ -0,0 +1,225 @@
import { describe, expect, it, vi } from 'vitest';
import {
addSocketListener,
closeInfo,
normalizeReconnect,
rawToString,
unwrapEventPayload,
unwrapMessagePayload,
WEBSOCKET_CLOSED,
WEBSOCKET_OPEN,
} from '../src/client/websocket-utils';
import type { WebSocketLike } from '../src/client/websocket-types';
function stubSocket(extra: Partial<WebSocketLike> = {}): WebSocketLike {
return {
readyState: 0,
send() {},
close() {},
...extra,
};
}
describe('websocket readyState constants', () => {
it('matches the standard WebSocket readyState values', () => {
expect(WEBSOCKET_OPEN).toBe(1);
expect(WEBSOCKET_CLOSED).toBe(3);
});
});
describe('normalizeReconnect', () => {
it('treats a disabled or omitted value as no reconnect policy', () => {
expect(normalizeReconnect(false)).toBeNull();
expect(normalizeReconnect(undefined)).toBeNull();
});
it('turns a boolean enable flag into an empty options object', () => {
expect(normalizeReconnect(true)).toEqual({});
});
it('returns the given reconnect options object unchanged', () => {
const options = { retries: 4, minDelayMs: 250, maxDelayMs: 8_000 };
expect(normalizeReconnect(options)).toBe(options);
expect(normalizeReconnect({ retries: 0 })).toEqual({ retries: 0 });
expect(normalizeReconnect({})).toEqual({});
});
});
describe('addSocketListener', () => {
it('binds and unbinds through addEventListener when present', () => {
const listener = vi.fn();
const socket = stubSocket({
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
on: vi.fn(),
});
const off = addSocketListener(socket, 'message', listener);
expect(socket.addEventListener).toHaveBeenCalledTimes(1);
expect(socket.addEventListener).toHaveBeenCalledWith('message', listener);
expect(socket.on).not.toHaveBeenCalled();
off();
expect(socket.removeEventListener).toHaveBeenCalledTimes(1);
expect(socket.removeEventListener).toHaveBeenCalledWith('message', listener);
});
it('does not throw on cleanup when removeEventListener is absent', () => {
const socket = stubSocket({ addEventListener: vi.fn() });
const off = addSocketListener(socket, 'open', vi.fn());
expect(off).not.toThrow();
});
it('binds through on() and unbinds through off() when addEventListener is missing', () => {
const listener = vi.fn();
const socket = stubSocket({
on: vi.fn(),
off: vi.fn(),
removeListener: vi.fn(),
});
const off = addSocketListener(socket, 'close', listener);
expect(socket.on).toHaveBeenCalledTimes(1);
expect(socket.on).toHaveBeenCalledWith('close', listener);
off();
expect(socket.off).toHaveBeenCalledTimes(1);
expect(socket.off).toHaveBeenCalledWith('close', listener);
expect(socket.removeListener).not.toHaveBeenCalled();
});
it('falls back to removeListener when off() is absent', () => {
const listener = vi.fn();
const socket = stubSocket({
on: vi.fn(),
removeListener: vi.fn(),
});
const off = addSocketListener(socket, 'error', listener);
off();
expect(socket.removeListener).toHaveBeenCalledTimes(1);
expect(socket.removeListener).toHaveBeenCalledWith('error', listener);
});
it('cleanup is a no-op when on() has neither off nor removeListener', () => {
const socket = stubSocket({ on: vi.fn() });
const off = addSocketListener(socket, 'message', vi.fn());
expect(off).not.toThrow();
});
it('returns a no-op cleanup when the socket has no listener APIs', () => {
const off = addSocketListener(stubSocket(), 'open', vi.fn());
expect(off).not.toThrow();
});
});
describe('unwrapMessagePayload', () => {
it('returns the data field from a JSON object envelope', () => {
expect(unwrapMessagePayload({ data: '{"ok":true}' })).toBe('{"ok":true}');
expect(unwrapMessagePayload({ data: { text: 'hi' } })).toEqual({ text: 'hi' });
expect(unwrapMessagePayload({ data: 0 })).toBe(0);
expect(unwrapMessagePayload({ data: undefined })).toBeUndefined();
});
it('returns the original value when it is not a data envelope', () => {
expect(unwrapMessagePayload('raw-text')).toBe('raw-text');
expect(unwrapMessagePayload(null)).toBeNull();
expect(unwrapMessagePayload([{ data: 1 }])).toEqual([{ data: 1 }]);
expect(unwrapMessagePayload({ type: 'message' })).toEqual({ type: 'message' });
});
});
describe('unwrapEventPayload', () => {
it('returns the error field from a JSON object envelope', () => {
expect(unwrapEventPayload({ error: 'socket failed' })).toBe('socket failed');
expect(unwrapEventPayload({ error: { message: 'boom' } })).toEqual({ message: 'boom' });
expect(unwrapEventPayload({ error: undefined })).toBeUndefined();
});
it('returns the original value when it is not an error envelope', () => {
expect(unwrapEventPayload('plain-error')).toBe('plain-error');
expect(unwrapEventPayload(null)).toBeNull();
expect(unwrapEventPayload([{ error: 1 }])).toEqual([{ error: 1 }]);
expect(unwrapEventPayload({ type: 'error' })).toEqual({ type: 'error' });
});
});
describe('rawToString', () => {
it('returns strings unchanged', () => {
expect(rawToString('{"echo":1}')).toBe('{"echo":1}');
expect(rawToString('')).toBe('');
});
it('decodes ArrayBuffer and ArrayBufferView payloads as UTF-8', () => {
const bytes = Uint8Array.from([0x68, 0x69]);
expect(rawToString(bytes.buffer)).toBe('hi');
expect(rawToString(bytes)).toBe('hi');
expect(rawToString(Buffer.from([0x68, 0x69]))).toBe('hi');
expect(rawToString(new DataView(bytes.buffer))).toBe('hi');
expect(rawToString(Uint8Array.from([0x21, 0x68, 0x69, 0x21]).subarray(1, 3))).toBe('hi');
expect(rawToString(new ArrayBuffer(0))).toBe('');
});
it('rejects Blob payloads that cannot be read synchronously', () => {
expect(() => rawToString(new Blob(['hi']))).toThrow(
'Blob WebSocket messages are not supported synchronously',
);
});
it('uses toString() on objects and String() on primitives', () => {
expect(rawToString({ toString: () => 'from-toString' })).toBe('from-toString');
expect(rawToString([1, 2])).toBe('1,2');
expect(rawToString({ a: 1 })).toBe('[object Object]');
expect(rawToString(42)).toBe('42');
expect(rawToString(false)).toBe('false');
expect(rawToString(null)).toBe('null');
expect(rawToString(undefined)).toBe('undefined');
});
});
describe('closeInfo', () => {
it('reads code and reason from a CloseEvent-like object', () => {
expect(closeInfo([{ code: 1000, reason: 'normal', wasClean: true }])).toEqual({
code: 1000,
reason: 'normal',
});
expect(closeInfo([{ code: 1001 }])).toEqual({
code: 1001,
reason: undefined,
});
expect(closeInfo([{ reason: 'going away' }])).toEqual({
code: undefined,
reason: 'going away',
});
expect(closeInfo([{ code: '1000', reason: 1 }])).toEqual({
code: undefined,
reason: undefined,
});
});
it('reads positional Node-style close arguments', () => {
expect(closeInfo([1006, 'abnormal'])).toEqual({
code: 1006,
reason: 'abnormal',
});
expect(closeInfo([1000])).toEqual({
code: 1000,
reason: undefined,
});
expect(closeInfo(['1000', 1])).toEqual({
code: undefined,
reason: undefined,
});
expect(closeInfo([])).toEqual({
code: undefined,
reason: undefined,
});
expect(closeInfo([[1000, 'nested']])).toEqual({
code: undefined,
reason: undefined,
});
});
});