refactor(onebot): merge element toSegment/fromSegment into one codec table
阶段 2(零行为改动):把「同一种消息元素」的两个 onebot 方向——收·转
(to-segment) 与 发·解(message-parser)——从两个文件各写各的分支,合并到一张
按元素类型索引的 ELEMENT_CODECS 表,每种类型一条 { toSegment?, fromSegment? }。
- 新增 event-converter/element-codecs.ts:13 类 toSegment + 14 类 fromSegment
逐字平移自原实现;私有 helper intOr/marketFaceElement/pickMediaSource 移来并导出。
- to-segment.ts:elementToSegment 改查表 + 保留原 default 透传兜底。
- message-parser.ts:segmentToElement 保留 9 个纯输入糖 case 作前置 normalize,
真实类型改查表,末尾保留原 unsupported warn。
- onebot 对账测试升级为按表键核对 S/P(比正则更硬),并断言真实类型 case 不再
残留于 parser、输入糖仍在。
行为 byte 级不变:onebot 全量 513 全绿、typecheck 干净;对抗性 Agent 逐字比对
确认无漂移、无运行时循环依赖。
This commit is contained in:
4 files changed
+465
-357
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import { parseFromCQString } from './helper/cq';
|
||||
import { ELEMENT_CODECS, intOr } from './event-converter/element-codecs';
|
||||
import type { JsonValue } from './types';
|
||||
|
||||
const log = createLogger('MsgParser');
|
||||
@@ -17,27 +18,6 @@ export interface ParseMessageOptions {
|
||||
|
||||
export const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
|
||||
|
||||
function intOr(value: unknown, fallback = 0): number {
|
||||
if (value === undefined || value === null) return fallback;
|
||||
if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback;
|
||||
const n = parseInt(String(value), 10);
|
||||
return Number.isFinite(n) ? n : fallback;
|
||||
}
|
||||
|
||||
/** Build a market-face (`mface`) element from an OneBot segment's data.
|
||||
* Shared by the dedicated `mface` segment and the `image`-with-`emoji_id`
|
||||
* round-trip path. `emojiId` is the hex GUID the wire builder converts back
|
||||
* to `MarketFace.faceId`. */
|
||||
function marketFaceElement(emojiId: string, data: Record<string, unknown>): MessageElement {
|
||||
return {
|
||||
type: 'mface',
|
||||
text: String(data.summary ?? data.name ?? ''),
|
||||
emojiId,
|
||||
emojiPackageId: intOr(data.emoji_package_id ?? data.tab_id, 0),
|
||||
emojiKey: String(data.key ?? ''),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseCQParams(raw: string): Record<string, string> {
|
||||
const params: Record<string, string> = {};
|
||||
if (!raw) return params;
|
||||
@@ -54,32 +34,6 @@ export function parseCQParams(raw: string): Record<string, string> {
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the best loadable source from a media segment's `file` / `url` / `path`
|
||||
* / `media` fields.
|
||||
*
|
||||
* `file` is normally the canonical OneBot field and wins, but it can also be a
|
||||
* QQ-internal media id (e.g. `<md5>.png`) that this process cannot resolve to a
|
||||
* local path. When a bot framework echoes a received image back (Yunzai et al.
|
||||
* resend the original `file=<md5>.ext` together with the download `url`), using
|
||||
* `file` makes the send path `statSync` the id as a bogus local path and throw
|
||||
* `ENOENT`. So: keep `file` when it is a directly loadable source (inline
|
||||
* bytes, a remote url, or a filesystem path with a separator); otherwise, if a
|
||||
* real http(s) `url` accompanies it, prefer that. (issue #155)
|
||||
*/
|
||||
function pickMediaSource(data: Record<string, unknown>): string {
|
||||
const file = String(data.file ?? '').trim();
|
||||
const url = String(data.url ?? '').trim();
|
||||
const fallback = file || url || String(data.path ?? '').trim() || String(data.media ?? '').trim();
|
||||
if (!file) return fallback;
|
||||
// `file` is itself loadable: inline bytes, a remote url, or a path (anything
|
||||
// carrying a `/` or `\` separator, incl. file:// and absolute/relative paths).
|
||||
if (/^(base64:\/\/|data:|https?:\/\/|file:\/\/)/i.test(file) || /[\\/]/.test(file)) return file;
|
||||
// `file` is a bare token (QQ-internal id) — fall back to a real url if present.
|
||||
if (/^https?:\/\//i.test(url)) return url;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// --- JSON segment parsing ---
|
||||
|
||||
interface MessageSegment {
|
||||
@@ -96,130 +50,11 @@ function isSegmentArray(val: unknown): val is MessageSegment[] {
|
||||
|
||||
export async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
|
||||
const normalizedType = type.toLowerCase();
|
||||
|
||||
// 纯 OneBot 输入糖:不是某种真实消息元素,只是被塌缩成 json/face/poke 的输入
|
||||
// 便利(或 forward 组装用的中间 node),无收侧对应、无专属 wire 形态,故不进
|
||||
// codec 表 —— 在这里前置处理。真实元素(收发同名)走下方的 ELEMENT_CODECS。
|
||||
switch (normalizedType) {
|
||||
case 'text': {
|
||||
const text = String(data.text ?? '');
|
||||
return text ? { type: 'text', text } : null;
|
||||
}
|
||||
case 'face': {
|
||||
const id = intOr(data.id, -1);
|
||||
if (id < 0) return null;
|
||||
return { type: 'face', faceId: id };
|
||||
}
|
||||
case 'at': {
|
||||
const qq = String(data.qq ?? '').trim();
|
||||
if (qq === 'all') {
|
||||
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
|
||||
}
|
||||
const uin = intOr(qq, 0);
|
||||
if (uin <= 0) return null;
|
||||
|
||||
const name = String(data.name ?? data.nickname ?? data.card ?? '').trim();
|
||||
let uid = String(data.uid ?? '').trim();
|
||||
if (!uid && options?.resolveMentionUid) {
|
||||
uid = (await options.resolveMentionUid(uin))?.trim() ?? '';
|
||||
}
|
||||
const element: MessageElement = { type: 'at', targetUin: uin };
|
||||
if (uid) element.uid = uid;
|
||||
if (name) element.text = `@${name} `;
|
||||
return element;
|
||||
}
|
||||
case 'reply': {
|
||||
const id = intOr(data.id, 0);
|
||||
if (id === 0) return null;
|
||||
|
||||
if (options?.resolveReplySequence) {
|
||||
const resolved = options.resolveReplySequence(id);
|
||||
if (typeof resolved === 'number' && resolved > 0) {
|
||||
const element: MessageElement = {
|
||||
type: 'reply',
|
||||
replySeq: resolved,
|
||||
replyMessageId: id // Keep the original messageId for logging
|
||||
};
|
||||
|
||||
// Try to get additional meta info for better reply display
|
||||
if (options?.resolveReplyMeta) {
|
||||
const meta = options.resolveReplyMeta(id);
|
||||
if (meta) {
|
||||
element.replySenderUin = meta.senderUin;
|
||||
element.replyTime = meta.time;
|
||||
element.replyRandom = meta.random;
|
||||
}
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
// Backward-compatible path: allow direct seq reply IDs.
|
||||
return id > 0 ? { type: 'reply', replySeq: id } : null;
|
||||
}
|
||||
case 'image': {
|
||||
// A market face that was surfaced as an `image` (see to-segment) can be
|
||||
// echoed straight back: when `emoji_id` is present we rebuild the market
|
||||
// face instead of re-uploading the gif as a plain picture.
|
||||
const imgEmojiId = String(data.emoji_id ?? '').trim();
|
||||
if (imgEmojiId) return marketFaceElement(imgEmojiId, data);
|
||||
return {
|
||||
type: 'image',
|
||||
url: pickMediaSource(data),
|
||||
flash: data.type === 'flash',
|
||||
subType: intOr(data.subType, 0),
|
||||
summary: data.summary ? String(data.summary) : undefined,
|
||||
};
|
||||
}
|
||||
case 'mface': {
|
||||
// Market face (商城表情). emoji_id is the hex GUID; without it we can't
|
||||
// construct the wire element, so drop the segment.
|
||||
const emojiId = String(data.emoji_id ?? '').trim();
|
||||
if (!emojiId) {
|
||||
log.warn('[MsgParser] mface segment without emoji_id is unsupported');
|
||||
return null;
|
||||
}
|
||||
return marketFaceElement(emojiId, data);
|
||||
}
|
||||
case 'record': {
|
||||
const source = pickMediaSource(data);
|
||||
if (!source) return null;
|
||||
return {
|
||||
type: 'record',
|
||||
url: source,
|
||||
};
|
||||
}
|
||||
case 'video': {
|
||||
const source = pickMediaSource(data);
|
||||
if (!source) return null;
|
||||
return {
|
||||
type: 'video',
|
||||
url: source,
|
||||
thumbUrl: data.thumb ? String(data.thumb) : undefined,
|
||||
};
|
||||
}
|
||||
case 'json': {
|
||||
return {
|
||||
type: 'json',
|
||||
text: String(data.data ?? ''),
|
||||
};
|
||||
}
|
||||
case 'xml': {
|
||||
return {
|
||||
type: 'xml',
|
||||
text: String(data.data ?? ''),
|
||||
subType: intOr(data.id, 0),
|
||||
};
|
||||
}
|
||||
case 'poke': {
|
||||
return {
|
||||
type: 'poke',
|
||||
faceId: intOr(data.type ?? data.id, 0),
|
||||
};
|
||||
}
|
||||
case 'forward': {
|
||||
return {
|
||||
type: 'forward',
|
||||
resId: String(data.id ?? ''),
|
||||
};
|
||||
}
|
||||
case 'node': {
|
||||
// Fake forward node segment — store the raw data for later processing
|
||||
// The content field may be a segment array, a single segment, or a CQ string
|
||||
@@ -232,12 +67,6 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
resId: JSON.stringify(data.content ?? ''),
|
||||
};
|
||||
}
|
||||
case 'markdown': {
|
||||
return {
|
||||
type: 'markdown',
|
||||
text: String(data.content ?? ''),
|
||||
};
|
||||
}
|
||||
case 'share': {
|
||||
// Link share — map to json card message
|
||||
const url = String(data.url ?? '');
|
||||
@@ -349,30 +178,15 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
// Anonymous flag — ignored during send, the protocol handles anonymity
|
||||
return null;
|
||||
}
|
||||
case 'file': {
|
||||
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
|
||||
const source = String(data.file ?? data.url ?? data.path ?? '').trim();
|
||||
if (!fileId && !source) {
|
||||
log.warn('[MsgParser] file segment without file_id or file/url is unsupported');
|
||||
return null;
|
||||
}
|
||||
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
|
||||
const fileSize = intOr(data.size ?? data.fileSize, 0);
|
||||
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
|
||||
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
|
||||
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
|
||||
const elem: MessageElement = fileId ? { type: 'file', fileId } : { type: 'file', url: source };
|
||||
if (fileName) elem.fileName = fileName;
|
||||
if (fileSize > 0) elem.fileSize = fileSize;
|
||||
if (md5Hex) elem.md5Hex = md5Hex;
|
||||
if (sha1Hex) elem.sha1Hex = sha1Hex;
|
||||
if (fileHash) elem.fileHash = fileHash;
|
||||
return elem;
|
||||
}
|
||||
default:
|
||||
console.warn(`[MsgParser] unsupported segment type: ${type}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// 真实元素(P 发·解,段 type 与 element.type 同名):查 codec 表。
|
||||
// 见 event-converter/element-codecs.ts。
|
||||
const codec = ELEMENT_CODECS[normalizedType];
|
||||
if (codec?.fromSegment) return codec.fromSegment(data, options);
|
||||
|
||||
console.warn(`[MsgParser] unsupported segment type: ${type}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
function segmentPayload(seg: MessageSegment): Record<string, unknown> {
|
||||
|
||||
Reference in new issue
Block a user