feat: add async SQLite on Node 24 and improve messaging diagnostics (#520)

Move database work off the main thread on Node.js 24 and improve message handling and runtime diagnostics.

Preserve migration, restart, and concurrency coverage with the async SQLite driver.
This commit is contained in:
MliKiowa authored and GitHub committed 2026-10-13 10:12:47 +08:00
1 parent 20f48d11ec
commit c7428363cb
170 files changed
+7748 -3913

No files matched your search

+9
View File
@@ -1,5 +1,14 @@
# Changelog
## Unreleased
- Breaking: require Node.js 24 or newer.
- Add `CustomReplySegment` and `message.customReply()` for inline quote previews inside merged-forward nodes.
- Expose optional inline content and quote metadata on received `ReplySegment` values.
- Reject CQ serialization of nested custom-reply content instead of silently stringifying message objects.
- Preserve string custom-reply content and metadata when parsing CQ strings.
- Decode CQ parameters once so literal entity text such as `,` survives round trips.
## 0.1.0
- Initial SnowLuma TypeScript SDK package.
+30
View File
@@ -162,6 +162,8 @@ const chainedCq = toCQString(chained);
const parsed = fromCQString('hi[CQ:at,qq=all]');
```
CQ 转换会保留参数中的字面量转义文本,例如图片路径中的 `,`,不会将它再次解码成逗号。
链式入口返回 `MessageChain`,可以直接传给发送接口,也可以用 `build()` / `toSegments()` 转成 OneBot segment 数组:
```ts
@@ -176,6 +178,34 @@ await text('hi').atAll().br().face(14).sendToGroup(bot, 123456);
已内置常用段:`text`、`br`、`face`、`at`、`atAll`、`reply`、`image`、`record`、`video`、`json`、`xml`、`poke`、`forward`、`node`、`share`、`music`、`location`、`contact` 和 `raw`。
### 合并转发中的自定义引用
合并转发节点的 `content` 支持 `reply.data.message`,无需引用目标已存在于本地消息库。
SDK 提供 `message.customReply()`(返回消息段,仅用于转发节点):
```ts
await bot.raw('send_group_forward_msg', {
group_id: 123456,
messages: [message.node(10001, '发送者', [
message.customReply([message.text('SnowLuma')], { qq: 10002, time: 1700000000, seq: 42 }),
message.text('这是回复内容'),
])],
});
```
对应的 OneBot JSON 为 `{ "type": "reply", "data": { "message": [{ "type": "text", "data": { "text": "SnowLuma" } }] } }`。
`message` 可以是文本/CQ 字符串、单个消息段或消息段数组,不能为空;显式提供时优先于 `id`。
引用预览保留文字和 @,图片、表情、语音、视频、文件、转发、JSON/XML 卡片和 Markdown 使用类型文字摘要,不会为引用重新上传媒体。
引用内容不支持嵌套 `reply`/`node` 或 `music`、`contact`、`poke` 等其他类型;无效内容会返回参数错误。
`qq`、`time`、`seq` 支持整数或整数字符串。省略时分别使用当前节点发送者、节点时间(未指定时为当前时间)和 `1`。
`qq` 必须是正安全整数,`time` 是 0 到 4294967295 的 Unix 秒,`seq` 是 1 到 4294967295 的序号。
这些字段用于引用预览;自定义引用不保证能在 QQ 中跳转到原消息。请使用 JSON 消息段传递此扩展;SDK 的 `toCQString` 会拒绝将嵌套消息段转换成 CQ 参数,避免内容被转成 `[object Object]`。
`get_forward_msg` 的回复段仍含 `id`;当 QQ 返回内嵌引用内容时,还会包含 `message` 以及可用的 `qq`、`time`、`seq`。
将返回节点的 `message` 作为新转发节点的 `content` 即可保留引用预览,无需再通过 `get_msg` 查询引用 ID。
若 QQ 没有提供引用内容,则只返回原有 `id`。普通群聊/私聊的 `reply.data.id` 用法保持不变。
## 请求控制
每次请求都支持覆盖 `echo`、超时和 `AbortSignal`:
+1 -1
View File
@@ -43,4 +43,4 @@ If the package version already exists on npm, the workflow skips publishing that
## Action Compatibility
SnowLuma action coverage is synchronized from `packages/core/src/onebot/actions/*.ts`. Adding an action type is a minor change unless it changes an existing method signature or return type.
SnowLuma action coverage is synchronized from `packages/onebot/src/actions/*.ts`. Adding an action type is a minor change unless it changes an existing method signature or return type.
+1 -1
View File
@@ -85,7 +85,7 @@
"access": "public"
},
"engines": {
"node": ">=22"
"node": ">=24"
},
"devDependencies": {
"@types/node": "catalog:",
+8 -16
View File
@@ -76,7 +76,7 @@ export class MessageChain<THasReply extends boolean = false> implements MessageC
}
reply(this: MessageChain<false>, id: number | string): MessageChain<true> {
return this.addSegment(segments.reply(id), 'reply') as MessageChain<true>;
return this.addSegment<true>(segments.reply(id));
}
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): MessageChain<THasReply> {
@@ -134,7 +134,7 @@ export class MessageChain<THasReply extends boolean = false> implements MessageC
type: TType,
data: TData,
): MessageChain<THasReply> {
return this.addSegment(segments.raw(type, data), type);
return this.addSegment(segments.raw(type, data));
}
append(messageInput: OutgoingMessage): MessageChain<THasReply> {
@@ -146,7 +146,7 @@ export class MessageChain<THasReply extends boolean = false> implements MessageC
}
for (const segment of normalized) {
next = next.addFromSegment(segment);
next = next.addSegment(segment);
}
return next;
@@ -192,24 +192,16 @@ export class MessageChain<THasReply extends boolean = false> implements MessageC
return this.items[Symbol.iterator]();
}
private addFromSegment(segment: AnyMessageSegment): MessageChain<THasReply> {
return this.addSegment(segment, segment.type);
}
private addSegment<TNextReply extends boolean = THasReply>(
segment: AnyMessageSegment,
singleUseType?: string,
): MessageChain<TNextReply> {
if (singleUseType && SINGLE_USE_TYPES.has(singleUseType) && this.used.has(singleUseType)) {
throw new Error(`Message segment "${singleUseType}" can only appear once in a chain`);
}
const nextUsed = new Set(this.used);
if (singleUseType && SINGLE_USE_TYPES.has(singleUseType)) {
nextUsed.add(singleUseType);
const singleUse = SINGLE_USE_TYPES.has(segment.type);
if (singleUse && this.used.has(segment.type)) {
throw new Error(`Message segment "${segment.type}" can only appear once in a chain`);
}
const nextUsed = singleUse ? new Set(this.used).add(segment.type) : this.used;
return new MessageChain<TNextReply>([...this.items, segment], nextUsed);
}
}
+11 -3
View File
@@ -1,4 +1,4 @@
import type { KnownMessageSegment, MessageSegment } from '../types/index';
import type { AnyMessageSegment } from '../types/index';
export function escapeCqText(text: string): string {
return text.replace(/&/g, '&amp;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;');
@@ -8,15 +8,23 @@ export function escapeCqParam(text: string): string {
return escapeCqText(text).replace(/,/g, '&#44;');
}
export function segmentsToCQString(segments: Array<KnownMessageSegment | MessageSegment>): string {
export function segmentsToCQString(segments: AnyMessageSegment[]): string {
return segments.map(segmentToCq).join('');
}
function segmentToCq(segment: KnownMessageSegment | MessageSegment): string {
function segmentToCq(segment: AnyMessageSegment): string {
if (segment.type === 'text') {
return escapeCqText(String(segment.data.text ?? ''));
}
if (
segment.type === 'reply' &&
segment.data.message !== undefined &&
typeof segment.data.message !== 'string'
) {
throw new TypeError('reply.message containing message segments must be sent as JSON');
}
const params = Object.entries(segment.data)
.filter(([, value]) => value !== undefined && value !== null)
.map(([key, value]) => `${key}=${escapeCqParam(String(value))}`)
+16 -24
View File
@@ -6,10 +6,6 @@ import type { AnyMessageSegment, FaceSegment, OutgoingMessage } from '../types/i
const CQ_REGEX = /\[CQ:([a-zA-Z0-9_.-]+)(?:,([^\]]*))?\]/g;
export function toCQString(input: OutgoingMessage): string {
if (typeof input === 'string') {
return escapeCqText(input);
}
const normalized = normalizeMessage(input);
return typeof normalized === 'string'
? escapeCqText(normalized)
@@ -21,31 +17,18 @@ export function fromCQString(input: string) {
let lastIndex = 0;
for (const match of input.matchAll(CQ_REGEX)) {
const index = match.index ?? 0;
const index = match.index;
if (index > lastIndex) {
const textValue = cqUnescape(input.slice(lastIndex, index));
if (textValue) {
current = current.text(textValue);
}
}
const segment = segmentFromCq(match[1] ?? '', parseCQParams(match[2] ?? ''));
if (segment) {
current = current.append(segment);
current = current.text(cqUnescape(input.slice(lastIndex, index)));
}
current = current.append(segmentFromCq(match[1]!, parseCQParams(match[2] ?? '')));
lastIndex = index + match[0].length;
}
if (lastIndex < input.length) {
const textValue = cqUnescape(input.slice(lastIndex));
if (textValue) {
current = current.text(textValue);
}
current = current.text(cqUnescape(input.slice(lastIndex)));
}
return current;
@@ -80,10 +63,11 @@ function cqUnescape(text: string): string {
}
function cqUnescapeParam(text: string): string {
return cqUnescape(text).replace(/&#44;/g, ',');
// Decode ampersands last so literal entity text is not decoded twice.
return cqUnescape(text.replace(/&#44;/g, ','));
}
function segmentFromCq(type: string, data: Record<string, string>): AnyMessageSegment | null {
function segmentFromCq(type: string, data: Record<string, string>): AnyMessageSegment {
switch (type) {
case 'text':
return segments.text(data.text ?? '');
@@ -120,8 +104,16 @@ function segmentFromCq(type: string, data: Record<string, string>): AnyMessageSe
: segments.raw(type, data);
}
case 'reply':
case 'reply': {
const { message, ...metadata } = data;
if (message !== undefined) {
return segments.customReply(message, metadata);
}
return segments.reply(data.id ?? '0');
}
case 'image':
return segments.image(data.file ?? data.url ?? '', {
url: data.url,
+9
View File
@@ -1,6 +1,7 @@
import type {
AtSegment,
ContactSegment,
CustomReplySegment,
FaceSegment,
ForwardSegment,
ImageSegment,
@@ -54,6 +55,14 @@ export const segments = {
return seg('reply', { id: String(id) });
},
/** An inline quote preview for use inside a merged-forward node. */
customReply(
message: CustomReplySegment['data']['message'],
options: Omit<CustomReplySegment['data'], 'message'> = {},
): CustomReplySegment {
return seg('reply', { ...options, message });
},
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): ImageSegment {
return seg('image', { file, ...options });
},
+10 -2
View File
@@ -14,7 +14,15 @@ export type FaceSegment = MessageSegment<
{ id: string; large?: boolean; resultId?: string }
>;
export type AtSegment = MessageSegment<'at', { qq: string; name?: string; uid?: string }>;
export type ReplySegment = MessageSegment<'reply', { id: string }>;
type ReplyContent = {
/** Inline quote preview; supported only inside merged-forward nodes. */
message: string | AnyMessageSegment | AnyMessageSegment[];
qq?: string | number;
time?: string | number;
seq?: string | number;
};
export type ReplySegment = MessageSegment<'reply', { id: string } & Partial<ReplyContent>>;
export type CustomReplySegment = MessageSegment<'reply', { id?: string } & ReplyContent>;
export type ImageSegment = MessageSegment<
'image',
{
@@ -98,7 +106,7 @@ export type KnownMessageSegment =
| LocationSegment
| ContactSegment;
export type AnyMessageSegment = KnownMessageSegment | MessageSegment;
export type AnyMessageSegment = KnownMessageSegment | CustomReplySegment | MessageSegment;
export interface MessageChainLike {
readonly length: number;
+27
View File
@@ -72,6 +72,33 @@ describe('MessageChain', () => {
expect(parseSegments('[CQ:reply,id=7]')).toEqual([{ type: 'reply', data: { id: '7' } }]);
});
it.each([
message.image('literal&#44;&amp;#44;.png'),
message.customReply('literal &#44; [CQ:at,qq=all] &[],'),
message.raw('extension', { value: '&#91;&#93;&#44;&amp; &[],' }),
])('decodes CQ parameters exactly once for $type', (segment) => {
expect(parseSegments(toCQString(segment))).toEqual([segment]);
});
it('preserves string custom replies and their metadata through CQ conversion', () => {
const reply = message.customReply('hello[CQ:at,qq=all] & goodbye', {
id: '-123',
qq: '10001',
time: '1700000000',
seq: '42',
});
expect(parseSegments(toCQString(reply))).toEqual([reply]);
const inline = message.customReply('quoted');
expect(parseSegments(toCQString(inline))).toEqual([inline]);
});
it.each([[message.text('quoted')], message.text('quoted')].map((content) => ({ content })))(
'rejects nested custom replies during CQ conversion ($content)',
({ content }) => {
expect(() => toCQString(message.customReply(content))).toThrow(/must be sent as JSON/);
},
);
it('can send itself through a compatible client', async () => {
const client = {
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 1 }),
+27
View File
@@ -73,6 +73,33 @@ describe('segments.reply', () => {
});
});
describe('segments.customReply', () => {
it('builds an inline quote without requiring a cached message id', () => {
expect(
segments.customReply([segments.text('SnowLuma')], {
qq: 10001,
time: 1700000000,
seq: 42,
}),
).toEqual({
type: 'reply',
data: {
message: [{ type: 'text', data: { text: 'SnowLuma' } }],
qq: 10001,
time: 1700000000,
seq: 42,
},
});
});
it('accepts a plain quote string without metadata', () => {
expect(segments.customReply('quoted')).toEqual({
type: 'reply',
data: { message: 'quoted' },
});
});
});
describe('segments.image', () => {
it('uses only the file when no options are given', () => {
expect(segments.image('/tmp/a.png')).toEqual({