feat(sdk): add media sends, quoted replies, and event waits

Add local media upload-and-send helpers with an optional Node file source
and stage-aware errors. Add explicit quoted replies and cancellable event
waits while preserving existing methods and handler contracts.

Propagate group-file publication failures instead of reporting success.
Cover cancellation, cleanup, signed message IDs, package exports, consumer
types, and real HTTP/WebSocket upload-to-send integration.

Validation: pnpm run ci (6231 tests passed, 9 skipped); SDK package contents
verified with npm pack --dry-run --ignore-scripts.
This commit is contained in:
DrSmoothl committed 2026-10-23 19:45:47 +08:00
1 parent 2d659b0ceb
commit fa5efcd310
28 files changed
+1798 -37

No files matched your search

+133
View File
@@ -1,6 +1,7 @@
import { createSnowLumaApiError, SnowLumaConnectionError } from '../errors.js';
import { normalizeMessage } from '../messages/index.js';
import { downloadFileStream, uploadFileStream } from './file-streams.js';
import { sendUploadedMedia } from './media.js';
import type {
ActionParams,
ActionResult,
@@ -17,8 +18,14 @@ import type {
GetMediaParams,
JsonObject,
JsonValue,
MediaSource,
OutgoingMessage,
RequestOptions,
SendFileOptions,
SendGroupFileOptions,
SendImageOptions,
SendRecordOptions,
SendVideoOptions,
SendMsgParams,
SetGroupReactionParams,
SnowLumaAction,
@@ -156,6 +163,132 @@ export abstract class SnowLumaApiClient {
);
}
/** Uploads local bytes, then sends an image message using the server's file path. */
sendGroupImage(groupId: number, source: MediaSource, options: SendImageOptions = {}) {
const { signal, timeoutMs, echo } = options;
return sendUploadedMedia(this, source, options, (upload) =>
this.sendGroupMessage(
groupId,
{ type: 'image', data: { ...options.image, file: upload.file_path } },
{
signal,
timeoutMs,
echo,
},
),
);
}
/** Uploads local bytes, then sends a record message using the server's file path. */
sendGroupRecord(groupId: number, source: MediaSource, options: SendRecordOptions = {}) {
const { signal, timeoutMs, echo } = options;
return sendUploadedMedia(this, source, options, (upload) =>
this.sendGroupMessage(
groupId,
{ type: 'record', data: { ...options.record, file: upload.file_path } },
{
signal,
timeoutMs,
echo,
},
),
);
}
/** Uploads local bytes, then sends a video message using the server's file path. */
sendGroupVideo(groupId: number, source: MediaSource, options: SendVideoOptions = {}) {
const { signal, timeoutMs, echo } = options;
return sendUploadedMedia(this, source, options, (upload) =>
this.sendGroupMessage(
groupId,
{ type: 'video', data: { ...options.video, file: upload.file_path } },
{
signal,
timeoutMs,
echo,
},
),
);
}
/** Uploads local bytes, then sends an image message using the server's file path. */
sendPrivateImage(userId: number, source: MediaSource, options: SendImageOptions = {}) {
const { signal, timeoutMs, echo } = options;
return sendUploadedMedia(this, source, options, (upload) =>
this.sendPrivateMessage(
userId,
{ type: 'image', data: { ...options.image, file: upload.file_path } },
{
signal,
timeoutMs,
echo,
},
),
);
}
/** Uploads local bytes, then sends a record message using the server's file path. */
sendPrivateRecord(userId: number, source: MediaSource, options: SendRecordOptions = {}) {
const { signal, timeoutMs, echo } = options;
return sendUploadedMedia(this, source, options, (upload) =>
this.sendPrivateMessage(
userId,
{ type: 'record', data: { ...options.record, file: upload.file_path } },
{
signal,
timeoutMs,
echo,
},
),
);
}
/** Uploads local bytes, then sends a video message using the server's file path. */
sendPrivateVideo(userId: number, source: MediaSource, options: SendVideoOptions = {}) {
const { signal, timeoutMs, echo } = options;
return sendUploadedMedia(this, source, options, (upload) =>
this.sendPrivateMessage(
userId,
{ type: 'video', data: { ...options.video, file: upload.file_path } },
{
signal,
timeoutMs,
echo,
},
),
);
}
/** Uploads local bytes and publishes a file in the group. */
sendGroupFile(groupId: number, source: MediaSource, options: SendGroupFileOptions = {}) {
const { signal, timeoutMs, echo, folder, folderId } = options;
return sendUploadedMedia(this, source, options, (upload) =>
this.uploadGroupFile(groupId, upload.file_path, {
signal,
timeoutMs,
echo,
folder,
folderId,
name: options.name ?? upload.file_name,
uploadFile: true,
}),
);
}
/** Uploads local bytes and sends the file to a private conversation. */
sendPrivateFile(userId: number, source: MediaSource, options: SendFileOptions = {}) {
const { signal, timeoutMs, echo } = options;
return sendUploadedMedia(this, source, options, (upload) =>
this.uploadPrivateFile(userId, upload.file_path, {
signal,
timeoutMs,
echo,
name: options.name ?? upload.file_name,
uploadFile: true,
}),
);
}
getMessage(messageId: number, options?: RequestOptions) {
return this.call('get_msg', { message_id: messageId }, options);
}
+1
View File
@@ -4,6 +4,7 @@ export { SnowLumaWebSocketClient, createWebSocketClient } from './websocket-clie
export type { SnowLumaHttpClientOptions } from './http-client.js';
export type {
EventWaitOptions,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
+48
View File
@@ -0,0 +1,48 @@
import { SnowLumaMediaSendError } from '../errors.js';
import { throwIfAborted } from '../internal/abort.js';
import type {
MediaSource,
UploadFileStreamComplete,
UploadFileStreamOptions,
} from '../types/index.js';
import type { SnowLumaApiClient } from './api-client.js';
/** Upload and send are separate operations; never retry a possibly completed send. */
export async function sendUploadedMedia<TResult>(
client: SnowLumaApiClient,
input: MediaSource,
options: UploadFileStreamOptions,
send: (upload: UploadFileStreamComplete) => Promise<TResult>,
): Promise<TResult> {
let upload: UploadFileStreamComplete;
try {
throwIfAborted(options.signal);
if (typeof input !== 'object' || input === null) {
throw new TypeError('Media source must contain bytes; use localFile() for local paths');
}
const source = 'source' in input ? input.source : input;
const filename =
'source' in input
? input.filename
: source instanceof Blob && 'name' in source && typeof source.name === 'string'
? source.name
: undefined;
upload = await client.uploadFileStream(source, {
...options,
filename: options.filename ?? filename,
});
} catch (cause) {
throw new SnowLumaMediaSendError('upload', cause);
}
try {
// Cancellation can arrive with the final upload ACK, before dispatching the send.
throwIfAborted(options.signal);
return await send(upload);
} catch (cause) {
throw new SnowLumaMediaSendError('send', cause, upload);
}
}
+150 -4
View File
@@ -17,11 +17,12 @@ import {
matchCommand,
noticeType,
requestType,
type CommandHandler,
type CommandHandler as BaseCommandHandler,
type CommandOptions,
type EventHandler,
type EventMiddleware,
type EventHandler as BaseEventHandler,
type EventMiddleware as BaseEventMiddleware,
type EventPredicate,
type SnowLumaEventContextWithQuote,
} from '../events/index.js';
import { SnowLumaApiClient, toJsonObject } from './api-client.js';
import { createRequestAbortState, raceWithAbort, throwIfAborted } from '../internal/abort.js';
@@ -68,6 +69,7 @@ import type {
WsRole,
} from '../types/index.js';
import type {
EventWaitOptions,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
@@ -76,6 +78,7 @@ import type {
} from './websocket-types.js';
export type {
EventWaitOptions,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
@@ -95,6 +98,16 @@ interface PendingRequest {
reject(error: Error): void;
}
type EventHandler<TEvent extends SnowLumaEvent = SnowLumaEvent> = BaseEventHandler<
TEvent,
SnowLumaEventContextWithQuote<TEvent>
>;
type EventMiddleware = BaseEventMiddleware<SnowLumaEventContextWithQuote>;
type CommandHandler = BaseCommandHandler<
OneBotMessageEvent,
SnowLumaEventContextWithQuote<OneBotMessageEvent>
>;
/** OneBot WebSocket client for SnowLuma APIs and realtime events. */
export class SnowLumaWebSocketClient extends SnowLumaApiClient {
readonly url: string;
@@ -107,6 +120,7 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
private readonly reconnect: ReconnectOptions | null;
private readonly emitter = new Emitter<SnowLumaWebSocketEvents>();
private readonly pending = new Map<string, PendingRequest>();
private readonly eventWaits = new Set<(error: Error) => void>();
private readonly middlewares: EventMiddleware[] = [];
private connection: SocketConnection | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
@@ -163,6 +177,129 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
return this.on('event', listener);
}
/** Waits for a future public event after middleware, without connecting or replaying events. */
waitForEvent<TEvent extends SnowLumaEvent>(
predicate: EventPredicate<TEvent>,
options?: EventWaitOptions,
): Promise<TEvent>;
waitForEvent(
predicate: ((event: SnowLumaEvent) => boolean) | undefined,
options?: EventWaitOptions,
): Promise<SnowLumaEvent>;
waitForEvent(options?: EventWaitOptions): Promise<SnowLumaEvent>;
waitForEvent(
predicateOrOptions?: ((event: SnowLumaEvent) => boolean) | EventWaitOptions,
requestedOptions?: EventWaitOptions,
): Promise<SnowLumaEvent> {
const predicate = typeof predicateOrOptions === 'function' ? predicateOrOptions : undefined;
const options =
typeof predicateOrOptions === 'function'
? requestedOptions
: (predicateOrOptions ?? requestedOptions);
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
return new Promise((resolve, reject) => {
throwIfAborted(options?.signal, 'SnowLuma event wait aborted');
if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > 2_147_483_647) {
throw new RangeError('Event wait timeoutMs must be between 0 and 2147483647');
}
let settled = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const cleanup = (): void => {
off();
this.eventWaits.delete(fail);
clearTimeout(timer);
options?.signal?.removeEventListener('abort', onAbort);
};
const fail = (error: unknown): void => {
if (settled) {
return;
}
settled = true;
cleanup();
reject(error);
};
const onAbort = (): void => {
fail(
new SnowLumaAbortError('SnowLuma event wait aborted', {
cause: options?.signal?.reason,
}),
);
};
const off = this.onEvent((event) => {
if (settled) {
return;
}
try {
const matched = predicate ? predicate(event) : true;
if (typeof matched !== 'boolean') {
throw new TypeError(
'Event wait predicates must return a boolean synchronously',
);
}
if (matched && !settled) {
settled = true;
cleanup();
resolve(event);
}
} catch (error) {
fail(error);
}
});
this.eventWaits.add(fail);
options?.signal?.addEventListener('abort', onAbort, { once: true });
if (timeoutMs > 0) {
timer = setTimeout(() => {
fail(
new SnowLumaTimeoutError(
`SnowLuma event wait timed out after ${timeoutMs}ms`,
timeoutMs,
),
);
}, timeoutMs);
}
});
}
/** Waits for a future message or message_sent event that passes the optional predicate. */
waitForMessage<TEvent extends OneBotMessageEvent>(
predicate: (event: OneBotMessageEvent) => event is TEvent,
options?: EventWaitOptions,
): Promise<TEvent>;
waitForMessage(
predicate: ((event: OneBotMessageEvent) => boolean) | undefined,
options?: EventWaitOptions,
): Promise<OneBotMessageEvent>;
waitForMessage(options?: EventWaitOptions): Promise<OneBotMessageEvent>;
waitForMessage(
predicateOrOptions?: ((event: OneBotMessageEvent) => boolean) | EventWaitOptions,
requestedOptions?: EventWaitOptions,
): Promise<OneBotMessageEvent> {
const predicate = typeof predicateOrOptions === 'function' ? predicateOrOptions : undefined;
const options =
typeof predicateOrOptions === 'function'
? requestedOptions
: (predicateOrOptions ?? requestedOptions);
return this.waitForEvent(
(event): event is OneBotMessageEvent =>
isMessageEvent(event) && (predicate ? predicate(event) : true),
options,
);
}
/** Adds event middleware to the dispatch pipeline. */
use(middleware: EventMiddleware): () => void {
this.middlewares.push(middleware);
@@ -341,6 +478,7 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
this.connection = null;
connection?.dispose(error);
this.rejectPending(error);
this.rejectEventWaits(error);
if (connection && connection.socket.readyState !== WEBSOCKET_CLOSED) {
const off = addSocketListener(connection.socket, 'close', (...args) => {
@@ -642,7 +780,9 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
private handleClose(args: unknown[]): void {
const info = closeInfo(args);
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket closed'));
const error = new SnowLumaConnectionError('SnowLuma WebSocket closed');
this.rejectPending(error);
this.rejectEventWaits(error);
this.emitter.emit('close', info);
if (!this.closedByUser && this.reconnect) {
@@ -688,6 +828,12 @@ export class SnowLumaWebSocketClient extends SnowLumaApiClient {
pending.reject(error);
}
}
private rejectEventWaits(error: Error): void {
for (const fail of this.eventWaits) {
fail(error);
}
}
}
export function createWebSocketClient(
@@ -40,6 +40,14 @@ export interface SnowLumaWebSocketClientOptions extends SnowLumaClientOptions {
reconnect?: boolean | ReconnectOptions;
}
/** Controls one wait for a future event, without opening a connection. */
export interface EventWaitOptions {
/** Defaults to the client's requestTimeoutMs. Set to 0 to wait without a deadline. */
timeoutMs?: number;
/** Cancels the wait without closing the connection. */
signal?: AbortSignal;
}
export interface WebSocketCloseInfo {
code?: number;
reason?: string;