Files
SnowLuma/packages/bridge/src/element-builder.ts
T
DrSmoothl f7a03ca05a refactor(bridge): extract protocol layer into @snowluma/bridge package
Phase 2 of the 4-package split (RoadMap #3). Moves ~35 files —
events / event-bus / identity-service / packet-pipeline / element-
builder / bridge-oidb / qq-info / msg-push/* / highway/* / web/* +
the bridge-side formatters — out of `packages/core/src/bridge/`
into the new `@snowluma/bridge` workspace package. Everything that
translates QQ wire bytes ↔ typed events/elements now lives there.

Why
---
- `packages/core/src/bridge/` was actually two layers: a low-level
  "protocol decoder + I/O" set (msg-push, highway, packet-pipeline,
  identity, element-builder) AND the Api-class host (bridge.ts +
  apis/*). The Api layer can't move without the protocol layer
  moving first, but the two had grown into one directory.
- Bridge-internal consumers (highway uploaders, OIDB envelope
  helper, element-builder, msg-push parsers) only ever needed
  `bridge.identity` + `bridge.sendRawPacket` + the upload-metadata
  cache. Splitting them out lets that minimal surface live in the
  bridge package as `BridgeContext` while the api-layer's extended
  context (with `apis: ApiHub`) stays in @snowluma/core.

What stays in @snowluma/core (apis layer):
  - bridge.ts          ── the god-class that composes the protocol
                          building blocks + mounts apis
  - bridge-interface.ts ── public façade for OneBot consumers
  - manager.ts          ── per-uin BridgeManager hub
  - apis/*              ── the 13 typed Api classes
  - bridge-context.ts (NEW) ── extends @snowluma/bridge's slim
                              BridgeContext with `apis: ApiHub` so
                              the 13 Api classes keep their typed
                              `this.ctx.apis.X.method()` access.

Layout
------
Moved via `git mv` (history preserved):
  events / event-bus / identity-service / packet-pipeline /
  element-builder / bridge-oidb / qq-info / msg-push/* /
  highway/* / web/*           → @snowluma/bridge/<sub>
  utils/event-format.ts        → @snowluma/bridge/format.ts

  (the last one renamed because the destination directory only has
  bridge-related files; `format.ts` reads cleaner than `event-format`.
  Listed as a rename in git's `RM` output — content unchanged.)

Layering fixes (functionality preserved, just type signatures)
--------------------------------------------------------------
- `element-builder.SendContext.bridge` → typed as `BridgeContext`
  instead of `Bridge`. Reads only `bridge.identity` and the
  upload-cache (both on BridgeContext); the concrete `Bridge`
  instance still passes via free upcast.
- `bridge-oidb.runOidb` signature widened from `Bridge` to
  `BridgeContext` — same reason.
- `highway/{highway-client,pipeline,image-upload,ptt-upload,
  video-upload}.ts` — same.
- `format.ts::formatReply` parameter typed as a new local
  `ReplyEventLookup` structural type (`{ findEvent(id): JsonObject |
  null }`) instead of `MessageStore` from @snowluma/onebot. The
  OneBot `MessageStore` is a structural superset; consumers pass
  it through unchanged.
- JSON value types moved to a new `@snowluma/common/json` subpath
  (consumed by format.ts) — `onebot/types.ts` re-exports them so
  external `import { JsonValue } from '<…>/onebot/types'` paths
  keep working.
- `UploadedFileMeta` interface moved from `core/src/bridge/bridge.ts`
  into `@snowluma/bridge/bridge-context.ts` — element-builder + the
  forward-builder both read the upload cache through BridgeContext,
  so the type has to live in @snowluma/bridge. `bridge.ts` keeps
  its re-export for back-compat.

Changes
-------
- New package `packages/bridge/` (package.json with per-file subpath
  exports mirroring legacy `core/src/bridge/<x>` layout 1:1,
  tsconfig.json, typecheck script).
- 35 `.ts` files moved via `git mv` (3 files counted by git as
  RM — rename + modify because Bridge → BridgeContext type swap).
- 150+ import sites rewritten across `packages/core/src` and
  `packages/core/tests`: `'../bridge/<x>'`, `'../../bridge/<x>'`,
  `'../src/bridge/<x>'`, `'@/bridge/web/<x>'`, and vitest
  `vi.mock(...)` literals all collapse to `@snowluma/bridge/<x>`.
- `@snowluma/core` depends on `@snowluma/bridge` (workspace:*).
- `@snowluma/bridge` depends on `@snowluma/common`,
  `@snowluma/proto-defs`, `@snowluma/proton`.
- `packages/core/src/utils/` directory removed (empty).

Verification
------------
- Full workspace `pnpm -r typecheck`: all 10 projects clean.
- core test suite: 552 passed / 552 total (pre-existing
  websocket-darwin-arm64.node addon failure unchanged — same
  baseline as the previous refactor commits).
- Vite build (with stubbed native binary): clean — 143 modules,
  2.84 MB bundle / 224 KB gzip, identical envelope to the
  pre-split build.

Phase 3 (next): OneBot + WebUI move into @snowluma/onebot. The
runnable `index.ts` stays in @snowluma/core as the application
entry, importing `OneBotManager` from `@snowluma/onebot`.
2026-05-21 08:41:34 +08:00

453 lines
15 KiB
TypeScript

import { protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from './bridge-context';
import type { MessageElement } from './events';
import { uploadImageMsgInfo } from './highway/image-upload';
import { hexToBytes } from './highway/pipeline';
import { uploadPttMsgInfo } from './highway/ptt-upload';
import { uploadVideoMsgInfo } from './highway/video-upload';
import type {
MarkdownData,
MentionExtraSend,
} from '@snowluma/proto-defs/action';
import type { Elem, GroupFileExtra } from '@snowluma/proto-defs/element';
type ProtoElem = Partial<Elem>;
export interface SendContext {
bridge: BridgeContext;
groupId?: number;
userUid?: string;
/**
* Set by the forward-message upload path. When `true`, file segments
* are encoded as receive-side wire shapes (group → `transElem(24)`,
* c2c → caller writes `body.msgContent` separately) instead of being
* dropped. The QQ-NT server rejects outgoing PbSendMsg with
* `transElem(24)` (result=79), but the long-msg upload service does
* NOT — it stores the gzipped protobuf verbatim, so the receiver
* can walk it back through the regular decoder. Mirrors NapCat's
* `PacketMsgFileElement.buildElement` + `buildContent` split (see
* `dev/napcatQQ/.../packet/message/element.ts:530-610`).
*/
forwardFake?: boolean;
}
function makeTextElem(text: string): ProtoElem {
return {
text: { str: text } as any,
};
}
function makeFaceElem(faceId: number): ProtoElem {
return {
face: { index: faceId } as any,
};
}
function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string {
if (!ctx || !targetUin) return '';
if (ctx.groupId !== undefined) {
const member = ctx.bridge.identity.findGroupMember(ctx.groupId, targetUin);
return member?.card?.trim() || member?.nickname?.trim() || '';
}
const friend = ctx.bridge.identity.findFriend(targetUin);
return friend?.remark?.trim() || friend?.nickname?.trim() || '';
}
function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem {
const mentionAll = element.uid === 'all' || element.targetUin === 0;
const targetUin = element.targetUin ?? 0;
const extra = protobuf_encode<MentionExtraSend>({
type: mentionAll ? 1 : 2,
uin: mentionAll ? 0 : targetUin,
field5: 0,
uid: mentionAll ? 'all' : (element.uid ?? ''),
});
// Prefer an explicit display string from the caller; otherwise look the
// target up in the roster so QQ renders `@昵称` instead of `@QQ号`.
// Falls back to the bare uin when the roster doesn't know them yet.
let str = element.text;
if (!str) {
if (mentionAll) {
str = '@全体成员 ';
} else {
const name = resolveMentionDisplay(ctx, targetUin);
str = name ? `@${name} ` : `@${targetUin} `;
}
}
return {
text: {
str,
pbReserve: extra,
} as any,
};
}
function makeReplyElem(element: MessageElement): ProtoElem {
const seq = element.replySeq! & 0xFFFFFFFF;
const srcMsg: any = {
origSeqs: [seq],
};
// Add additional fields if available for better reply display
if (element.replySenderUin) {
srcMsg.senderUin = BigInt(element.replySenderUin);
}
if (element.replyTime) {
srcMsg.time = element.replyTime;
}
return { srcMsg };
}
function makeJsonElem(element: MessageElement): ProtoElem {
const content = element.text ?? '';
const payload = new Uint8Array(content.length + 1);
payload[0] = 0x00;
const encoded = new TextEncoder().encode(content);
payload.set(encoded, 1);
return {
richMsg: {
serviceId: 1,
template1: payload,
} as any,
};
}
function makeXmlElem(element: MessageElement): ProtoElem {
const content = element.text ?? '';
const payload = new Uint8Array(content.length + 1);
payload[0] = 0x00;
const encoded = new TextEncoder().encode(content);
payload.set(encoded, 1);
return {
richMsg: {
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
template1: payload,
} as any,
};
}
function makeMarkdownElem(element: MessageElement): ProtoElem {
const data = protobuf_encode<MarkdownData>({ content: element.text ?? '' });
return {
commonElem: {
serviceType: 45,
pbElem: data,
businessType: 1,
} as any,
};
}
function escapeXml(value: string): string {
return value
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}
function makeForwardElem(element: MessageElement): ProtoElem {
const resId = (element.resId ?? '').trim();
if (!resId) {
throw new Error('forward resId is required');
}
// Multi-msg preview bubble — modelled on the go-cqhttp / NapCat XML.
// `source` becomes the bold header (e.g. "群聊的聊天记录"), `news`
// entries become per-line previews ("nick: text"), `summary` is the
// grey footer ("查看 N 条转发消息"), `prompt` is the chat-list brief.
const source = element.forwardSource && element.forwardSource.length > 0
? element.forwardSource
: '聊天记录';
const summary = element.forwardSummary && element.forwardSummary.length > 0
? element.forwardSummary
: '查看转发消息';
const prompt = element.forwardPrompt && element.forwardPrompt.length > 0
? element.forwardPrompt
: '[聊天记录]';
const news = Array.isArray(element.forwardNews) ? element.forwardNews : [];
const tSum = element.forwardTSum && element.forwardTSum > 0
? element.forwardTSum
: Math.max(news.length, 1);
const newsTitles = news
.map(n => `<title size="26" color="#777777">${escapeXml(n.text ?? '')}</title>`)
.join('');
const resIdAttr = escapeXml(resId);
const xml =
`<?xml version="1.0" encoding="utf-8"?>` +
`<msg templateID="1" action="viewMultiMsg" serviceID="35"` +
` brief="${escapeXml(prompt)}"` +
` m_resid="${resIdAttr}" m_fileName="${resIdAttr}" actionData="${resIdAttr}"` +
` tSum="${tSum}" sourceMsgId="0" flag="3" adverSign="0" multiMsgFlag="0">` +
`<item layout="1">` +
`<title size="34" color="#000000">${escapeXml(source)}</title>` +
newsTitles +
`<hr hidden="false" style="0"/>` +
`<summary size="26" color="#808080">${escapeXml(summary)}</summary>` +
`</item>` +
`<source name="${escapeXml(source)}" icon="" action="" appid="-1"/>` +
`</msg>`;
const encodedXml = new TextEncoder().encode(xml);
const payload = new Uint8Array(encodedXml.length + 1);
payload[0] = 0x00;
payload.set(encodedXml, 1);
return {
richMsg: {
serviceId: 35,
template1: payload,
} as any,
};
}
async function makeImageElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
if (!isGroup && !targetIdOrUid) {
throw new Error('private image target uid is missing');
}
const msgInfo = await uploadImageMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 20 : 10,
} as any,
};
}
async function makePttElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
if (!isGroup && !targetIdOrUid) {
throw new Error('private record target uid is missing');
}
const msgInfo = await uploadPttMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 12=c2c, 22=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 22 : 12,
} as any,
};
}
/**
* Receive-side group file element shape — `transElem(elemType=24,
* elemValue: 0x01 | BE16(len) | GroupFileExtra)`.
*
* NOT used for outgoing PbSendMsg (the QQ-NT server rejects that with
* result=79); the group-file send-side flow goes through dedicated
* OIDB 0x6d9_4 via `bridge.apis.groupFile.publish`. This shape IS used
* inside the long-msg upload (forward / multi-msg) — the long-msg
* service stores the gzipped protobuf verbatim, and the receiver
* decodes file entities from `transElem(24)` (see
* `msg-push/rich-body-decoder.ts:169-187`).
*
* `ctx` is consulted to fill in size/name/md5/sha1 from the upload
* metadata cache when the caller only threaded the file_id through.
* Mirrors the c2c forward path in `apis/forward.ts::buildForwardPushBody`
* which already does this lookup — without it the receiver sees a
* "0 B" file with no name (OneBot11 `{type:'file', file_id}` segments
* typically omit the metadata since the upload action returned only
* the id).
*/
function makeGroupFileElem(element: MessageElement, ctx?: SendContext): ProtoElem {
if (!element.fileId) throw new Error('file element missing fileId');
const cached = ctx?.bridge.recallUploadedFile(element.fileId);
const fileSize = element.fileSize ?? cached?.fileSize ?? 0;
const fileName = element.fileName ?? cached?.fileName ?? '';
const md5 = element.md5Hex
? hexToBytes(element.md5Hex)
: (cached?.fileMd5 ?? new Uint8Array(0));
const sha1 = element.sha1Hex
? hexToBytes(element.sha1Hex)
: (cached?.fileSha1 ?? new Uint8Array(0));
// Outer field1 is hardcoded to 6 in NapCat's encoder
// (`packet/message/element.ts:589`). Inner GroupFileExtraInfo carries
// busId=102 + the file_id + name + size + sha1/md5 hashes.
const extraBytes = protobuf_encode<GroupFileExtra>({
field1: 6,
fileName,
inner: {
info: {
busId: 102,
fileId: element.fileId,
fileSize: BigInt(fileSize),
fileName,
fileSha: sha1,
extInfoString: '',
fileMd5: md5,
},
},
});
if (extraBytes.length > 0xFFFF) {
// The 16-bit length prefix caps the payload at 64 KiB; even the
// densest GroupFileExtra (fileId/name/two hashes) is well under.
throw new Error(`group file extra too large (${extraBytes.length} > 65535)`);
}
const elemValue = new Uint8Array(3 + extraBytes.length);
elemValue[0] = 0x01;
elemValue[1] = (extraBytes.length >> 8) & 0xff;
elemValue[2] = extraBytes.length & 0xff;
elemValue.set(extraBytes, 3);
return {
transElem: {
elemType: 24,
elemValue,
} as any,
};
}
async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise<ProtoElem> {
const isGroup = ctx.groupId !== undefined;
const targetIdOrUid = isGroup ? ctx.groupId! : (ctx.userUid ?? '');
if (!isGroup && !targetIdOrUid) {
throw new Error('private video target uid is missing');
}
const msgInfo = await uploadVideoMsgInfo(ctx.bridge, isGroup, targetIdOrUid, element);
// commonElem.businessType is the QQ NT scene tag the receive-side
// decoder pairs with: 11=c2c, 21=group. Sending the group tag on a
// c2c message bounces with PbSendMsg result=79.
return {
commonElem: {
serviceType: 48,
pbElem: msgInfo,
businessType: isGroup ? 21 : 11,
} as any,
};
}
/**
* Build proto Elem objects from an array of MessageElements.
* Supports: text, face, at, reply, json, xml, markdown, image, record, video, forward.
* Image, record and video elements trigger NTV2 highway upload via the SendContext.
*/
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
const result: ProtoElem[] = [];
for (const elem of elements) {
switch (elem.type) {
case 'text':
if (elem.text) result.push(makeTextElem(elem.text));
break;
case 'face':
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId));
break;
case 'at':
result.push(makeMentionElem(elem, ctx));
break;
case 'reply':
if (elem.replySeq) result.push(makeReplyElem(elem));
break;
case 'json':
if (elem.text) result.push(makeJsonElem(elem));
break;
case 'xml':
if (elem.text) result.push(makeXmlElem(elem));
break;
case 'markdown':
if (elem.text) result.push(makeMarkdownElem(elem));
break;
case 'image':
if (ctx) {
result.push(await makeImageElem(ctx, elem));
} else {
console.warn('[ElemBuilder] image send requires SendContext');
}
break;
case 'forward':
if (elem.resId) result.push(makeForwardElem(elem));
break;
case 'record':
if (ctx) {
result.push(await makePttElem(ctx, elem));
} else {
console.warn('[ElemBuilder] record send requires SendContext');
}
break;
case 'video':
if (ctx) {
result.push(await makeVideoElem(ctx, elem));
} else {
console.warn('[ElemBuilder] video send requires SendContext');
}
break;
case 'file':
// Files split into two routes depending on whether this is a
// live send or a forward-message fake-send:
//
// 1. LIVE send (PbSendMsg / OIDB 0x6d9_4) — never carried on
// elems[]. The OneBot layer splits file segments off before
// calling buildSendElems:
// * c2c (private): split → `bridge.sendC2cFileMessage`
// (routingHead.trans0x211 + msgContent FileExtra).
// * group: split → `bridge.sendGroupFileMessage`
// (OIDB 0x6d9_4 publish).
// The QQ-NT server REJECTS outgoing PbSendMsg with a
// transElem(24) (result=79), so an element reaching here
// in live-send mode is a routing bug — drop with a warn.
//
// 2. FORWARD-FAKE upload (long-msg) — `ctx.forwardFake===true`.
// The long-msg service stores the gzipped protobuf verbatim
// and the receiver decodes file entities from transElem(24)
// + msgContent FileExtra. Mirror NapCat's split (see
// `dev/napcatQQ/.../packet/message/element.ts:530-610`):
// * group → emit transElem(24) via makeGroupFileElem
// * c2c → emit NOTHING here; the forward-builder pulls
// the file segment off and writes msgContent
// separately (because RichText.notOnlineFile +
// FileExtra both live outside elems[]).
if (ctx && ctx.forwardFake) {
if (ctx.groupId !== undefined) {
result.push(makeGroupFileElem(elem, ctx));
}
// c2c forwardFake intentionally falls through — handled by
// the forward-builder at the msgContent level.
} else {
console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)');
}
break;
default:
console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`);
break;
}
}
return result;
}