diff --git a/README.md b/README.md index 11c5843b..3e416afe 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,8 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生 | TypeScript SDK | [`packages/sdk/README.md`](packages/sdk/README.md) | | MCP | [`packages/mcp/README.md`](packages/mcp/README.md) | +JSON 消息段接受标准的 `data.data` 字符串,也兼容 `data.data` 非数组对象和 `{ type: "json", data: "..." }` 简写;`data` 必填,最终内容必须是 JSON 对象。 + ## 开发 需要 Node.js 22.13+(23 系需 23.4+)与 pnpm 10.28.0,日常开发基于 `dev` 分支: diff --git a/packages/onebot/src/event-converter/element-codecs.ts b/packages/onebot/src/event-converter/element-codecs.ts index 3ad0fc45..0ede513e 100644 --- a/packages/onebot/src/event-converter/element-codecs.ts +++ b/packages/onebot/src/event-converter/element-codecs.ts @@ -318,11 +318,14 @@ export const ELEMENT_CODECS = { return { type: 'json', data: { data: element.text ?? '' } }; }, async fromSegment(data) { - const text = data.data; + const raw = data.data; + const text = typeof raw === 'object' && raw !== null && !Array.isArray(raw) + ? JSON.stringify(raw) + : raw; if (typeof text !== 'string' || !text.trim()) { throw new MessageElementValidationError( 'INVALID_FIELD', - 'message segment "json" field "data" must be a non-empty JSON string', + 'message segment "json" field "data" must be a JSON object or non-empty JSON string', 'json', 'data', ); diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 367ce7ec..9fa7d8d8 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -53,7 +53,7 @@ export function parseCQParams(raw: string): Record { interface MessageSegment { type: string; - data?: Record; + data?: unknown; [key: string]: unknown; } @@ -152,12 +152,18 @@ function validatedOutboundElement(element: MessageElement): MessageElement { function assertScalarSegmentData(type: string, data: Record): void { for (const [field, value] of Object.entries(data)) { + const isJsonObjectField = type === 'json' + && (field === 'data' || field === 'config') + && typeof value === 'object' + && value !== null + && !Array.isArray(value); if ( value === undefined || value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' + || isJsonObjectField ) continue; throw new MessageElementValidationError( 'INVALID_FIELD', @@ -207,11 +213,11 @@ function requireCoordinate( export async function segmentToElement(type: string, data: Record, options?: ParseMessageOptions): Promise { const normalizedType = normalizeSegmentType(type); - // Ordinary OneBot segment fields are scalar. Reject objects/arrays before - // codecs can stringify them into "[object Object]" and alter caller intent. - // Forward nodes deliberately own nested content but are rejected by their - // dedicated normal-send branch below; anonymous is rejected regardless of - // payload, so neither needs the scalar guard. + // Ordinary OneBot segment fields are scalar. JSON deliberately accepts its + // object-valued data/config compatibility fields; every other object/array + // is rejected before a codec can coerce it and alter caller intent. Forward + // nodes own nested content but are rejected by their dedicated normal-send + // branch below; anonymous is rejected regardless of payload. if (normalizedType !== 'node' && normalizedType !== 'anonymous') { assertScalarSegmentData(normalizedType, data); } @@ -415,6 +421,9 @@ function segmentPayload(seg: MessageSegment): Record { const topLevel = { ...seg } as Record; delete topLevel.type; delete topLevel.data; + if (normalizeSegmentType(seg.type) === 'json' && typeof seg.data === 'string') { + return { ...topLevel, data: seg.data }; + } const nested = (seg.data && typeof seg.data === 'object' && !Array.isArray(seg.data)) ? seg.data : {}; diff --git a/packages/onebot/tests/message-action-validation.test.ts b/packages/onebot/tests/message-action-validation.test.ts index a3662c10..95dc627f 100644 --- a/packages/onebot/tests/message-action-validation.test.ts +++ b/packages/onebot/tests/message-action-validation.test.ts @@ -88,6 +88,33 @@ describe('outbound message validation at the Action boundary', () => { expect(bridgeSend).not.toHaveBeenCalled(); }); + it('sends object-valued JSON cards from AstrBot-compatible clients', async () => { + const bridgeSend = vi.fn(async () => sendReceipt); + const ref = instanceContext(bridgeSend); + const api = new ApiHandler({ + sendGroupMessage: (groupId, message, autoEscape) => + sendGroupMessage(ref, groupId, message, autoEscape), + } as ApiActionContext); + + const response = await api.handle('send_group_msg', { + group_id: 12345, + message: [{ + type: 'json', + data: { + data: { app: 'com.tencent.music.lua', meta: { music: { title: '晴天' } } }, + config: { token: 'signed-token' }, + }, + }], + }); + + expect(response).toMatchObject({ status: 'ok', retcode: 0 }); + expect(bridgeSend).toHaveBeenCalledOnce(); + expect(bridgeSend.mock.calls[0]?.[1]).toEqual([{ + type: 'json', + text: '{"app":"com.tencent.music.lua","meta":{"music":{"title":"晴天"}}}', + }]); + }); + it('reports the public data field when a JSON segment uses data.text', async () => { const bridgeSend = vi.fn(); const ref = instanceContext(bridgeSend); @@ -107,7 +134,7 @@ describe('outbound message validation at the Action boundary', () => { expect(response).toMatchObject({ status: 'failed', retcode: 1400, - wording: 'message segment "json" field "data" must be a non-empty JSON string', + wording: 'message segment "json" field "data" must be a JSON object or non-empty JSON string', }); expect(bridgeSend).not.toHaveBeenCalled(); }); diff --git a/packages/onebot/tests/message-parser.test.ts b/packages/onebot/tests/message-parser.test.ts index b4413aae..09667f4e 100644 --- a/packages/onebot/tests/message-parser.test.ts +++ b/packages/onebot/tests/message-parser.test.ts @@ -168,7 +168,7 @@ describe('parseMessage', () => { )).resolves.toEqual([{ type: 'text', text: ' ' }]); }); - it('rejects object-valued fields instead of stringifying caller input', async () => { + it('rejects object-valued fields for scalar-only segments', async () => { await expect(parseMessage( [{ type: 'text', data: { text: { bad: true } } }] as any, false, @@ -177,14 +177,6 @@ describe('parseMessage', () => { elementType: 'text', field: 'text', }); - await expect(parseMessage( - [{ type: 'json', data: { data: { app: 'unexpected-object' } } }] as any, - false, - )).rejects.toMatchObject({ - code: 'INVALID_FIELD', - elementType: 'json', - field: 'data', - }); }); it('parses face segment', async () => { @@ -586,6 +578,52 @@ describe('parseMessage', () => { expect(result[0].text).toBe('{"app":"test"}'); }); + it('accepts an object JSON payload produced by AstrBot-compatible clients', async () => { + const result = await parseMessage( + [{ + type: 'json', + data: { + data: { + app: 'com.tencent.music.lua', + meta: { music: { title: '晴天' } }, + }, + config: { token: 'signed-token' }, + }, + }] as any, + false, + ); + + expect(result).toEqual([{ + type: 'json', + text: '{"app":"com.tencent.music.lua","meta":{"music":{"title":"晴天"}}}', + }]); + }); + + it('accepts the JSON raw-string segment shorthand used by compatible clients', async () => { + await expect(parseMessage( + [{ type: 'json', data: '{"app":"com.tencent.music.lua"}' }] as any, + false, + )).resolves.toEqual([{ + type: 'json', + text: '{"app":"com.tencent.music.lua"}', + }]); + }); + + it.each([ + { label: 'array', value: [] }, + { label: 'null', value: null }, + { label: 'number', value: 1 }, + ])('rejects a $label JSON payload instead of sending a non-object card', async ({ value }) => { + await expect(parseMessage( + [{ type: 'json', data: { data: value } }] as any, + false, + )).rejects.toMatchObject({ + code: 'INVALID_FIELD', + elementType: 'json', + field: 'data', + }); + }); + it('reads canonical xml resid and file_size fields', async () => { const xml = await parseMessage( [{ type: 'xml', data: { data: '', resid: '35' } }] as any,