This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

File diff suppressed because it is too large. Load diff
+104 -90
View File
@@ -1,115 +1,129 @@
import {
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaTransportError,
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaTransportError,
} from '../errors';
import { SnowLumaApiClient, toJsonObject } from './api-client';
import { createRequestAbortState, isAbortError } from '../internal/abort';
import { assertApiResponse } from '../internal/json';
import type {
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
RequestOptions,
SnowLumaAction,
SnowLumaClientOptions,
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
RequestOptions,
SnowLumaAction,
SnowLumaClientOptions,
} from '../types/index';
/** Options for the HTTP transport client. */
export interface SnowLumaHttpClientOptions extends SnowLumaClientOptions {
/** OneBot HTTP endpoint. Defaults to http://127.0.0.1:3000/. */
baseUrl?: string;
/** Custom fetch implementation for tests or non-standard runtimes. */
fetch?: typeof fetch;
/** Extra headers sent with every request. Authorization is managed by accessToken. */
headers?: Record<string, string>;
/** OneBot HTTP endpoint. Defaults to http://127.0.0.1:3000/. */
baseUrl?: string;
/** Custom fetch implementation for tests or non-standard runtimes. */
fetch?: typeof fetch;
/** Extra headers sent with every request. Authorization is managed by accessToken. */
headers?: Record<string, string>;
}
/** OneBot HTTP client for SnowLuma. */
export class SnowLumaHttpClient extends SnowLumaApiClient {
readonly baseUrl: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
readonly baseUrl: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
private readonly fetchImpl: typeof fetch;
private readonly headers: Record<string, string>;
private readonly fetchImpl: typeof fetch;
private readonly headers: Record<string, string>;
constructor(options: SnowLumaHttpClientOptions = {}) {
super();
this.baseUrl = options.baseUrl ?? 'http://127.0.0.1:3000/';
this.accessToken = options.accessToken;
this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
this.fetchImpl = options.fetch ?? globalThis.fetch;
this.headers = options.headers ?? {};
constructor(options: SnowLumaHttpClientOptions = {}) {
super();
this.baseUrl = options.baseUrl ?? 'http://127.0.0.1:3000/';
this.accessToken = options.accessToken;
this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
this.fetchImpl = options.fetch ?? globalThis.fetch;
this.headers = options.headers ?? {};
if (!this.fetchImpl) {
throw new SnowLumaConnectionError('No fetch implementation is available');
}
}
/** Sends one OneBot action over HTTP and returns the raw response envelope. */
override async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const abort = createRequestAbortState(timeoutMs, options?.signal);
try {
const response = await this.fetchImpl(this.baseUrl, {
method: 'POST',
headers: this.createHeaders(),
body: JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo: options?.echo,
}),
signal: abort.signal,
});
const text = await response.text();
let parsed: unknown;
try {
parsed = text ? JSON.parse(text) : null;
} catch (error) {
throw new SnowLumaParseError(`SnowLuma returned non-JSON HTTP ${response.status}`, { cause: error });
}
const apiResponse = assertApiResponse(parsed) as ApiResponse<ActionResult<TAction>>;
return apiResponse;
} catch (error) {
if (error instanceof SnowLumaTransportError) throw error;
if (isAbortError(error) || abort.signal.aborted) {
if (abort.isTimedOut()) {
throw new SnowLumaTimeoutError(`SnowLuma request timed out after ${timeoutMs}ms`, timeoutMs, { cause: error });
if (!this.fetchImpl) {
throw new SnowLumaConnectionError('No fetch implementation is available');
}
if (abort.isExternallyAborted()) {
throw new SnowLumaAbortError('SnowLuma request aborted', { cause: error });
}
}
throw new SnowLumaConnectionError('SnowLuma HTTP request failed', { cause: error });
} finally {
abort.cleanup();
}
}
private createHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
...this.headers,
};
if (this.accessToken) {
headers.Authorization = `Bearer ${this.accessToken}`;
/** Sends one OneBot action over HTTP and returns the raw response envelope. */
override async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const abort = createRequestAbortState(timeoutMs, options?.signal);
try {
const response = await this.fetchImpl(this.baseUrl, {
method: 'POST',
headers: this.createHeaders(),
body: JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo: options?.echo,
}),
signal: abort.signal,
});
const text = await response.text();
let parsed: unknown;
try {
parsed = text ? JSON.parse(text) : null;
} catch (error) {
throw new SnowLumaParseError(`SnowLuma returned non-JSON HTTP ${response.status}`, {
cause: error,
});
}
const apiResponse = assertApiResponse(parsed) as ApiResponse<ActionResult<TAction>>;
return apiResponse;
} catch (error) {
if (error instanceof SnowLumaTransportError) {
throw error;
}
if (isAbortError(error) || abort.signal.aborted) {
if (abort.isTimedOut()) {
throw new SnowLumaTimeoutError(
`SnowLuma request timed out after ${timeoutMs}ms`,
timeoutMs,
{ cause: error },
);
}
if (abort.isExternallyAborted()) {
throw new SnowLumaAbortError('SnowLuma request aborted', { cause: error });
}
}
throw new SnowLumaConnectionError('SnowLuma HTTP request failed', { cause: error });
} finally {
abort.cleanup();
}
}
private createHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
...this.headers,
};
if (this.accessToken) {
headers.Authorization = `Bearer ${this.accessToken}`;
}
return headers;
}
return headers;
}
}
export function createHttpClient(options?: SnowLumaHttpClientOptions): SnowLumaHttpClient {
return new SnowLumaHttpClient(options);
return new SnowLumaHttpClient(options);
}
+5 -5
View File
@@ -4,9 +4,9 @@ export { SnowLumaWebSocketClient, createWebSocketClient } from './websocket-clie
export type { SnowLumaHttpClientOptions } from './http-client';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './websocket-client';
+500 -392
View File
@@ -1,427 +1,535 @@
import {
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
} from '../errors';
import { Emitter } from '../emitter';
import {
createEventContext,
isBotStatusEvent,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
matchCommand,
noticeType,
requestType,
type CommandHandler,
type CommandOptions,
type EventHandler,
type EventMiddleware,
type EventPredicate,
createEventContext,
isBotStatusEvent,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
matchCommand,
noticeType,
requestType,
type CommandHandler,
type CommandOptions,
type EventHandler,
type EventMiddleware,
type EventPredicate,
} from '../events/index';
import { SnowLumaApiClient, toJsonObject } from './api-client';
import { raceWithAbort, throwIfAborted } from '../internal/abort';
import { appendAccessToken, assertApiResponse, createEcho, echoKey, isJsonObject } from '../internal/json';
import {
addSocketListener,
closeInfo,
normalizeReconnect,
rawToString,
unwrapEventPayload,
unwrapMessagePayload,
WEBSOCKET_CLOSED,
WEBSOCKET_OPEN,
appendAccessToken,
assertApiResponse,
createEcho,
echoKey,
isJsonObject,
} from '../internal/json';
import {
addSocketListener,
closeInfo,
normalizeReconnect,
rawToString,
unwrapEventPayload,
unwrapMessagePayload,
WEBSOCKET_CLOSED,
WEBSOCKET_OPEN,
} from './websocket-utils';
import type {
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
JsonValue,
OneBotBotStatusEvent,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotRequestEvent,
RequestOptions,
SnowLumaAction,
SnowLumaEvent,
WsRole,
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
JsonValue,
OneBotBotStatusEvent,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotRequestEvent,
RequestOptions,
SnowLumaAction,
SnowLumaEvent,
WsRole,
} from '../types/index';
import type {
PendingRequest,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketConstructor,
WebSocketLike,
PendingRequest,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketConstructor,
WebSocketLike,
} from './websocket-types';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './websocket-types';
/** OneBot WebSocket client for SnowLuma APIs and realtime events. */
export class SnowLumaWebSocketClient extends SnowLumaApiClient {
readonly url: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
readonly role: WsRole;
readonly url: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
readonly role: WsRole;
private readonly protocols?: string | string[];
private readonly WebSocketCtor: WebSocketConstructor;
private readonly reconnect: ReconnectOptions | null;
private readonly emitter = new Emitter<SnowLumaWebSocketEvents>();
private readonly pending = new Map<string, PendingRequest>();
private readonly middlewares: EventMiddleware[] = [];
private socket: WebSocketLike | null = null;
private connectPromise: Promise<void> | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempts = 0;
private closedByUser = false;
private readonly protocols?: string | string[];
private readonly WebSocketCtor: WebSocketConstructor;
private readonly reconnect: ReconnectOptions | null;
private readonly emitter = new Emitter<SnowLumaWebSocketEvents>();
private readonly pending = new Map<string, PendingRequest>();
private readonly middlewares: EventMiddleware[] = [];
private socket: WebSocketLike | null = null;
private connectPromise: Promise<void> | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempts = 0;
private closedByUser = false;
constructor(options: SnowLumaWebSocketClientOptions = {}) {
super();
this.url = options.url ?? 'ws://127.0.0.1:3001/';
this.accessToken = options.accessToken;
this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
this.role = options.role ?? 'Universal';
this.protocols = options.protocols;
this.WebSocketCtor = options.webSocket ?? globalThis.WebSocket as unknown as WebSocketConstructor;
this.reconnect = normalizeReconnect(options.reconnect);
constructor(options: SnowLumaWebSocketClientOptions = {}) {
super();
this.url = options.url ?? 'ws://127.0.0.1:3001/';
this.accessToken = options.accessToken;
this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
this.role = options.role ?? 'Universal';
this.protocols = options.protocols;
this.WebSocketCtor =
options.webSocket ?? (globalThis.WebSocket as unknown as WebSocketConstructor);
this.reconnect = normalizeReconnect(options.reconnect);
if (!this.WebSocketCtor) {
throw new SnowLumaConnectionError('No WebSocket implementation is available');
}
}
/** True when the underlying WebSocket is currently open. */
get isConnected(): boolean {
return this.socket?.readyState === WEBSOCKET_OPEN;
}
/** Subscribes to low-level client events. Returns an unsubscribe function. */
on<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): () => void {
return this.emitter.on(event, listener);
}
/** Subscribes to one low-level client event, then automatically unsubscribes. */
once<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): () => void {
return this.emitter.once(event, listener);
}
/** Removes a previously registered low-level client event listener. */
off<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): void {
this.emitter.off(event, listener);
}
/** Subscribes to every SnowLuma event packet. */
onEvent(listener: (event: SnowLumaEvent) => void): () => void {
return this.on('event', listener);
}
/** Adds event middleware to the dispatch pipeline. */
use(middleware: EventMiddleware): () => void {
this.middlewares.push(middleware);
return () => {
const index = this.middlewares.indexOf(middleware);
if (index >= 0) this.middlewares.splice(index, 1);
};
}
/** Runs a handler when a type guard or predicate matches an event. */
when<TEvent extends SnowLumaEvent>(
predicate: EventPredicate<TEvent>,
handler: EventHandler<TEvent>,
): () => void {
return this.use(async (event, context, next) => {
if (predicate(event)) {
await handler(event, context as never);
}
if (!context.stopped) await next();
});
}
onMessage(handler: EventHandler<OneBotMessageEvent>): () => void {
return this.when(isMessageEvent, handler);
}
onPrivateMessage(handler: EventHandler<Extract<OneBotMessageEvent, { message_type: 'private' }>>): () => void {
return this.when(isPrivateMessageEvent, handler);
}
onGroupMessage(handler: EventHandler<Extract<OneBotMessageEvent, { message_type: 'group' }>>): () => void {
return this.when(isGroupMessageEvent, handler);
}
onNotice(handler: EventHandler<OneBotNoticeEvent>): () => void;
onNotice(type: string, handler: EventHandler<OneBotNoticeEvent>): () => void;
onNotice(typeOrHandler: string | EventHandler<OneBotNoticeEvent>, handler?: EventHandler<OneBotNoticeEvent>): () => void {
if (typeof typeOrHandler === 'string') {
if (!handler) throw new TypeError('onNotice(type, handler) requires a handler');
return this.when(noticeType(typeOrHandler), handler);
}
return this.when(isNoticeEvent, typeOrHandler);
}
onBotStatus(handler: EventHandler<OneBotBotStatusEvent>): () => void {
return this.when(isBotStatusEvent, handler);
}
onRequest(handler: EventHandler<OneBotRequestEvent>): () => void;
onRequest(type: string, handler: EventHandler<OneBotRequestEvent>): () => void;
onRequest(typeOrHandler: string | EventHandler<OneBotRequestEvent>, handler?: EventHandler<OneBotRequestEvent>): () => void {
if (typeof typeOrHandler === 'string') {
if (!handler) throw new TypeError('onRequest(type, handler) requires a handler');
return this.when(requestType(typeOrHandler), handler);
}
return this.when(isRequestEvent, typeOrHandler);
}
onMetaEvent(handler: EventHandler<OneBotMetaEvent>): () => void {
return this.when(isMetaEvent, handler);
}
command(
command: string | RegExp,
handler: CommandHandler,
options?: CommandOptions,
): () => void {
return this.onMessage(async (event, context) => {
const matched = matchCommand(event, command, options);
if (!matched) return;
await handler(event, Object.assign(context, { command: matched }), matched);
});
}
/** Connects to SnowLuma's OneBot WebSocket endpoint. */
async connect(): Promise<void> {
if (this.isConnected) return;
if (this.connectPromise) return this.connectPromise;
this.closedByUser = false;
this.connectPromise = new Promise((resolve, reject) => {
const url = appendAccessToken(this.url, this.accessToken);
const socket = new this.WebSocketCtor(url, this.protocols);
this.socket = socket;
const cleanup = [
addSocketListener(socket, 'open', () => {
cleanup.forEach((off) => off());
this.bindSocket(socket);
this.reconnectAttempts = 0;
this.connectPromise = null;
this.emitter.emit('open', undefined);
resolve();
}),
addSocketListener(socket, 'error', (error) => {
this.emitter.emit('error', unwrapEventPayload(error));
}),
addSocketListener(socket, 'close', (...args) => {
cleanup.forEach((off) => off());
this.connectPromise = null;
this.socket = null;
reject(new SnowLumaConnectionError('SnowLuma WebSocket closed before opening'));
this.handleClose(args);
}),
];
});
return this.connectPromise;
}
/** Closes the socket and rejects all pending API requests. */
close(code = 1000, reason = 'normal'): void {
this.closedByUser = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket client closed'));
if (this.socket && this.socket.readyState !== WEBSOCKET_CLOSED) {
this.socket.close(code, reason);
}
this.socket = null;
this.connectPromise = null;
}
/** Sends one OneBot action over WebSocket and returns the raw response envelope. */
override async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
throwIfAborted(options?.signal);
await raceWithAbort(this.connect(), options?.signal, 'SnowLuma WebSocket request aborted before connection opened');
throwIfAborted(options?.signal);
const socket = this.socket;
if (!socket || socket.readyState !== WEBSOCKET_OPEN) {
throw new SnowLumaConnectionError('SnowLuma WebSocket is not open');
}
const echo = options?.echo ?? createEcho();
const key = echoKey(echo);
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const promise = new Promise<ApiResponse>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | null = null;
let abortListener: (() => void) | undefined;
const cleanup = (): void => {
if (timer) clearTimeout(timer);
if (abortListener) options?.signal?.removeEventListener('abort', abortListener);
};
timer = timeoutMs > 0
? setTimeout(() => {
this.pending.delete(key);
cleanup();
reject(new SnowLumaTimeoutError(`SnowLuma WebSocket request timed out after ${timeoutMs}ms`, timeoutMs));
}, timeoutMs)
: null;
abortListener = () => {
this.pending.delete(key);
cleanup();
reject(new SnowLumaAbortError('SnowLuma WebSocket request aborted', { cause: options?.signal?.reason }));
};
options?.signal?.addEventListener('abort', abortListener, { once: true });
this.pending.set(key, { resolve, reject, timer, cleanup });
});
try {
socket.send(JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo,
}));
} catch (error) {
const pending = this.pending.get(key);
pending?.cleanup?.();
this.pending.delete(key);
throw new SnowLumaConnectionError('Failed to send SnowLuma WebSocket request', { cause: error });
}
return promise as Promise<ApiResponse<ActionResult<TAction>>>;
}
private bindSocket(socket: WebSocketLike): void {
addSocketListener(socket, 'message', (...args) => this.handleMessage(args));
addSocketListener(socket, 'error', (error) => this.emitter.emit('error', unwrapEventPayload(error)));
addSocketListener(socket, 'close', (...args) => this.handleClose(args));
}
private handleMessage(args: unknown[]): void {
const raw = unwrapMessagePayload(args[0]);
this.emitter.emit('raw', raw);
let parsed: unknown;
try {
parsed = JSON.parse(rawToString(raw));
} catch (error) {
this.emitter.emit('error', new SnowLumaParseError('SnowLuma WebSocket returned non-JSON message', { cause: error }));
return;
}
if (isJsonObject(parsed) && parsed.echo !== undefined) {
const key = echoKey(parsed.echo as JsonValue);
const pending = this.pending.get(key);
if (pending) {
this.pending.delete(key);
pending.cleanup?.();
try {
const response = assertApiResponse(parsed);
pending.resolve(response);
this.emitter.emit('response', response);
} catch (error) {
pending.reject(new SnowLumaParseError('SnowLuma WebSocket response is invalid', { cause: error }));
if (!this.WebSocketCtor) {
throw new SnowLumaConnectionError('No WebSocket implementation is available');
}
return;
}
}
if (isJsonObject(parsed) && typeof parsed.post_type === 'string') {
void this.dispatchEvent(parsed as SnowLumaEvent).catch((error) => {
this.emitter.emit('error', error);
});
/** True when the underlying WebSocket is currently open. */
get isConnected(): boolean {
return this.socket?.readyState === WEBSOCKET_OPEN;
}
}
private async dispatchEvent(event: SnowLumaEvent): Promise<void> {
const context = createEventContext(event, this);
let index = -1;
const next = async (): Promise<void> => {
index += 1;
const middleware = this.middlewares[index];
if (!middleware || context.stopped) return;
await middleware(event, context, next);
};
await next();
if (!context.stopped && index >= this.middlewares.length - 1) {
this.emitter.emit('event', event);
/** Subscribes to low-level client events. Returns an unsubscribe function. */
on<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): () => void {
return this.emitter.on(event, listener);
}
}
private handleClose(args: unknown[]): void {
const info = closeInfo(args);
this.socket = null;
this.connectPromise = null;
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket closed'));
this.emitter.emit('close', info);
if (!this.closedByUser && this.reconnect) {
this.scheduleReconnect();
/** Subscribes to one low-level client event, then automatically unsubscribes. */
once<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): () => void {
return this.emitter.once(event, listener);
}
}
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
const reconnect = this.reconnect;
if (!reconnect) return;
const retries = reconnect.retries ?? Number.POSITIVE_INFINITY;
if (this.reconnectAttempts >= retries) return;
const minDelay = reconnect.minDelayMs ?? 1000;
const maxDelay = reconnect.maxDelayMs ?? 30_000;
const delay = Math.min(maxDelay, minDelay * 2 ** this.reconnectAttempts);
this.reconnectAttempts += 1;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
void this.connect().catch((error) => {
this.emitter.emit('error', error);
if (!this.closedByUser) this.scheduleReconnect();
});
}, delay);
}
private rejectPending(error: Error): void {
for (const pending of this.pending.values()) {
pending.cleanup?.();
pending.reject(error);
/** Removes a previously registered low-level client event listener. */
off<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): void {
this.emitter.off(event, listener);
}
/** Subscribes to every SnowLuma event packet. */
onEvent(listener: (event: SnowLumaEvent) => void): () => void {
return this.on('event', listener);
}
/** Adds event middleware to the dispatch pipeline. */
use(middleware: EventMiddleware): () => void {
this.middlewares.push(middleware);
return () => {
const index = this.middlewares.indexOf(middleware);
if (index >= 0) {
this.middlewares.splice(index, 1);
}
};
}
/** Runs a handler when a type guard or predicate matches an event. */
when<TEvent extends SnowLumaEvent>(
predicate: EventPredicate<TEvent>,
handler: EventHandler<TEvent>,
): () => void {
return this.use(async (event, context, next) => {
if (predicate(event)) {
await handler(event, context as never);
}
if (!context.stopped) {
await next();
}
});
}
onMessage(handler: EventHandler<OneBotMessageEvent>): () => void {
return this.when(isMessageEvent, handler);
}
onPrivateMessage(
handler: EventHandler<Extract<OneBotMessageEvent, { message_type: 'private' }>>,
): () => void {
return this.when(isPrivateMessageEvent, handler);
}
onGroupMessage(
handler: EventHandler<Extract<OneBotMessageEvent, { message_type: 'group' }>>,
): () => void {
return this.when(isGroupMessageEvent, handler);
}
onNotice(handler: EventHandler<OneBotNoticeEvent>): () => void;
onNotice(type: string, handler: EventHandler<OneBotNoticeEvent>): () => void;
onNotice(
typeOrHandler: string | EventHandler<OneBotNoticeEvent>,
handler?: EventHandler<OneBotNoticeEvent>,
): () => void {
if (typeof typeOrHandler === 'string') {
if (!handler) {
throw new TypeError('onNotice(type, handler) requires a handler');
}
return this.when(noticeType(typeOrHandler), handler);
}
return this.when(isNoticeEvent, typeOrHandler);
}
onBotStatus(handler: EventHandler<OneBotBotStatusEvent>): () => void {
return this.when(isBotStatusEvent, handler);
}
onRequest(handler: EventHandler<OneBotRequestEvent>): () => void;
onRequest(type: string, handler: EventHandler<OneBotRequestEvent>): () => void;
onRequest(
typeOrHandler: string | EventHandler<OneBotRequestEvent>,
handler?: EventHandler<OneBotRequestEvent>,
): () => void {
if (typeof typeOrHandler === 'string') {
if (!handler) {
throw new TypeError('onRequest(type, handler) requires a handler');
}
return this.when(requestType(typeOrHandler), handler);
}
return this.when(isRequestEvent, typeOrHandler);
}
onMetaEvent(handler: EventHandler<OneBotMetaEvent>): () => void {
return this.when(isMetaEvent, handler);
}
command(
command: string | RegExp,
handler: CommandHandler,
options?: CommandOptions,
): () => void {
return this.onMessage(async (event, context) => {
const matched = matchCommand(event, command, options);
if (!matched) {
return;
}
await handler(event, Object.assign(context, { command: matched }), matched);
});
}
/** Connects to SnowLuma's OneBot WebSocket endpoint. */
async connect(): Promise<void> {
if (this.isConnected) {
return;
}
if (this.connectPromise) {
return this.connectPromise;
}
this.closedByUser = false;
this.connectPromise = new Promise((resolve, reject) => {
const url = appendAccessToken(this.url, this.accessToken);
const socket = new this.WebSocketCtor(url, this.protocols);
this.socket = socket;
const cleanup = [
addSocketListener(socket, 'open', () => {
cleanup.forEach((off) => off());
this.bindSocket(socket);
this.reconnectAttempts = 0;
this.connectPromise = null;
this.emitter.emit('open', undefined);
resolve();
}),
addSocketListener(socket, 'error', (error) => {
this.emitter.emit('error', unwrapEventPayload(error));
}),
addSocketListener(socket, 'close', (...args) => {
cleanup.forEach((off) => off());
this.connectPromise = null;
this.socket = null;
reject(new SnowLumaConnectionError('SnowLuma WebSocket closed before opening'));
this.handleClose(args);
}),
];
});
return this.connectPromise;
}
/** Closes the socket and rejects all pending API requests. */
close(code = 1000, reason = 'normal'): void {
this.closedByUser = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket client closed'));
if (this.socket && this.socket.readyState !== WEBSOCKET_CLOSED) {
this.socket.close(code, reason);
}
this.socket = null;
this.connectPromise = null;
}
/** Sends one OneBot action over WebSocket and returns the raw response envelope. */
override async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
throwIfAborted(options?.signal);
await raceWithAbort(
this.connect(),
options?.signal,
'SnowLuma WebSocket request aborted before connection opened',
);
throwIfAborted(options?.signal);
const socket = this.socket;
if (!socket || socket.readyState !== WEBSOCKET_OPEN) {
throw new SnowLumaConnectionError('SnowLuma WebSocket is not open');
}
const echo = options?.echo ?? createEcho();
const key = echoKey(echo);
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const promise = new Promise<ApiResponse>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | null = null;
let abortListener: (() => void) | undefined;
const cleanup = (): void => {
if (timer) {
clearTimeout(timer);
}
if (abortListener) {
options?.signal?.removeEventListener('abort', abortListener);
}
};
timer =
timeoutMs > 0
? setTimeout(() => {
this.pending.delete(key);
cleanup();
reject(
new SnowLumaTimeoutError(
`SnowLuma WebSocket request timed out after ${timeoutMs}ms`,
timeoutMs,
),
);
}, timeoutMs)
: null;
abortListener = () => {
this.pending.delete(key);
cleanup();
reject(
new SnowLumaAbortError('SnowLuma WebSocket request aborted', {
cause: options?.signal?.reason,
}),
);
};
options?.signal?.addEventListener('abort', abortListener, { once: true });
this.pending.set(key, { resolve, reject, timer, cleanup });
});
try {
socket.send(
JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo,
}),
);
} catch (error) {
const pending = this.pending.get(key);
pending?.cleanup?.();
this.pending.delete(key);
throw new SnowLumaConnectionError('Failed to send SnowLuma WebSocket request', {
cause: error,
});
}
return promise as Promise<ApiResponse<ActionResult<TAction>>>;
}
private bindSocket(socket: WebSocketLike): void {
addSocketListener(socket, 'message', (...args) => this.handleMessage(args));
addSocketListener(socket, 'error', (error) =>
this.emitter.emit('error', unwrapEventPayload(error)),
);
addSocketListener(socket, 'close', (...args) => this.handleClose(args));
}
private handleMessage(args: unknown[]): void {
const raw = unwrapMessagePayload(args[0]);
this.emitter.emit('raw', raw);
let parsed: unknown;
try {
parsed = JSON.parse(rawToString(raw));
} catch (error) {
this.emitter.emit(
'error',
new SnowLumaParseError('SnowLuma WebSocket returned non-JSON message', {
cause: error,
}),
);
return;
}
if (isJsonObject(parsed) && parsed.echo !== undefined) {
const key = echoKey(parsed.echo as JsonValue);
const pending = this.pending.get(key);
if (pending) {
this.pending.delete(key);
pending.cleanup?.();
try {
const response = assertApiResponse(parsed);
pending.resolve(response);
this.emitter.emit('response', response);
} catch (error) {
pending.reject(
new SnowLumaParseError('SnowLuma WebSocket response is invalid', {
cause: error,
}),
);
}
return;
}
}
if (isJsonObject(parsed) && typeof parsed.post_type === 'string') {
void this.dispatchEvent(parsed as SnowLumaEvent).catch((error) => {
this.emitter.emit('error', error);
});
}
}
private async dispatchEvent(event: SnowLumaEvent): Promise<void> {
const context = createEventContext(event, this);
let index = -1;
const next = async (): Promise<void> => {
index += 1;
const middleware = this.middlewares[index];
if (!middleware || context.stopped) {
return;
}
await middleware(event, context, next);
};
await next();
if (!context.stopped && index >= this.middlewares.length - 1) {
this.emitter.emit('event', event);
}
}
private handleClose(args: unknown[]): void {
const info = closeInfo(args);
this.socket = null;
this.connectPromise = null;
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket closed'));
this.emitter.emit('close', info);
if (!this.closedByUser && this.reconnect) {
this.scheduleReconnect();
}
}
private scheduleReconnect(): void {
if (this.reconnectTimer) {
return;
}
const reconnect = this.reconnect;
if (!reconnect) {
return;
}
const retries = reconnect.retries ?? Number.POSITIVE_INFINITY;
if (this.reconnectAttempts >= retries) {
return;
}
const minDelay = reconnect.minDelayMs ?? 1000;
const maxDelay = reconnect.maxDelayMs ?? 30_000;
const delay = Math.min(maxDelay, minDelay * 2 ** this.reconnectAttempts);
this.reconnectAttempts += 1;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
void this.connect().catch((error) => {
this.emitter.emit('error', error);
if (!this.closedByUser) {
this.scheduleReconnect();
}
});
}, delay);
}
private rejectPending(error: Error): void {
for (const pending of this.pending.values()) {
pending.cleanup?.();
pending.reject(error);
}
this.pending.clear();
}
this.pending.clear();
}
}
export function createWebSocketClient(options?: SnowLumaWebSocketClientOptions): SnowLumaWebSocketClient {
return new SnowLumaWebSocketClient(options);
export function createWebSocketClient(
options?: SnowLumaWebSocketClientOptions,
): SnowLumaWebSocketClient {
return new SnowLumaWebSocketClient(options);
}
+41 -43
View File
@@ -1,64 +1,62 @@
import type {
ApiResponse,
SnowLumaClientOptions,
SnowLumaEvent,
WsRole,
} from '../types/index';
import type { ApiResponse, SnowLumaClientOptions, SnowLumaEvent, WsRole } from '../types/index';
export interface WebSocketLike {
readyState: number;
send(data: string): void;
close(code?: number, reason?: string): void;
addEventListener?: (event: string, listener: (...args: unknown[]) => void) => void;
removeEventListener?: (event: string, listener: (...args: unknown[]) => void) => void;
on?: (event: string, listener: (...args: unknown[]) => void) => void;
off?: (event: string, listener: (...args: unknown[]) => void) => void;
removeListener?: (event: string, listener: (...args: unknown[]) => void) => void;
readyState: number;
send(data: string): void;
close(code?: number, reason?: string): void;
addEventListener?: (event: string, listener: (...args: unknown[]) => void) => void;
removeEventListener?: (event: string, listener: (...args: unknown[]) => void) => void;
on?: (event: string, listener: (...args: unknown[]) => void) => void;
off?: (event: string, listener: (...args: unknown[]) => void) => void;
removeListener?: (event: string, listener: (...args: unknown[]) => void) => void;
}
export type WebSocketConstructor = new (url: string, protocols?: string | string[]) => WebSocketLike;
export type WebSocketConstructor = new (
url: string,
protocols?: string | string[],
) => WebSocketLike;
/** Reconnect policy for the WebSocket client. */
export interface ReconnectOptions {
/** Maximum reconnect attempts. Omit for unlimited retries. */
retries?: number;
/** Initial reconnect delay in milliseconds. Defaults to 1000. */
minDelayMs?: number;
/** Maximum reconnect delay in milliseconds. Defaults to 30000. */
maxDelayMs?: number;
/** Maximum reconnect attempts. Omit for unlimited retries. */
retries?: number;
/** Initial reconnect delay in milliseconds. Defaults to 1000. */
minDelayMs?: number;
/** Maximum reconnect delay in milliseconds. Defaults to 30000. */
maxDelayMs?: number;
}
/** Options for the WebSocket transport client. */
export interface SnowLumaWebSocketClientOptions extends SnowLumaClientOptions {
/** OneBot WebSocket endpoint. Defaults to ws://127.0.0.1:3001/. */
url?: string;
/** OneBot WebSocket role advertised by the client. */
role?: WsRole;
/** Optional WebSocket protocols argument. */
protocols?: string | string[];
/** Custom WebSocket constructor for Node runtimes or tests. */
webSocket?: WebSocketConstructor;
/** Enables or configures automatic reconnect after unexpected close. */
reconnect?: boolean | ReconnectOptions;
/** OneBot WebSocket endpoint. Defaults to ws://127.0.0.1:3001/. */
url?: string;
/** OneBot WebSocket role advertised by the client. */
role?: WsRole;
/** Optional WebSocket protocols argument. */
protocols?: string | string[];
/** Custom WebSocket constructor for Node runtimes or tests. */
webSocket?: WebSocketConstructor;
/** Enables or configures automatic reconnect after unexpected close. */
reconnect?: boolean | ReconnectOptions;
}
export interface WebSocketCloseInfo {
code?: number;
reason?: string;
code?: number;
reason?: string;
}
export interface SnowLumaWebSocketEvents {
open: undefined;
close: WebSocketCloseInfo;
error: unknown;
event: SnowLumaEvent;
response: ApiResponse;
raw: unknown;
open: undefined;
close: WebSocketCloseInfo;
error: unknown;
event: SnowLumaEvent;
response: ApiResponse;
raw: unknown;
}
export interface PendingRequest {
resolve: (response: ApiResponse) => void;
reject: (error: Error) => void;
timer: ReturnType<typeof setTimeout> | null;
cleanup?: () => void;
resolve: (response: ApiResponse) => void;
reject: (error: Error) => void;
timer: ReturnType<typeof setTimeout> | null;
cleanup?: () => void;
}
+81 -53
View File
@@ -1,77 +1,105 @@
import { isJsonObject } from '../internal/json';
import type {
ReconnectOptions,
WebSocketCloseInfo,
WebSocketLike,
} from './websocket-types';
import type { ReconnectOptions, WebSocketCloseInfo, WebSocketLike } from './websocket-types';
export const WEBSOCKET_OPEN = 1;
export const WEBSOCKET_CLOSED = 3;
export function normalizeReconnect(value: boolean | ReconnectOptions | undefined): ReconnectOptions | null {
if (!value) return null;
if (value === true) return {};
return value;
export function normalizeReconnect(
value: boolean | ReconnectOptions | undefined,
): ReconnectOptions | null {
if (!value) {
return null;
}
if (value === true) {
return {};
}
return value;
}
export function addSocketListener(
socket: WebSocketLike,
event: string,
listener: (...args: unknown[]) => void,
socket: WebSocketLike,
event: string,
listener: (...args: unknown[]) => void,
): () => void {
if (socket.addEventListener) {
socket.addEventListener(event, listener);
return () => socket.removeEventListener?.(event, listener);
}
if (socket.on) {
socket.on(event, listener);
return () => {
if (socket.off) socket.off(event, listener);
else socket.removeListener?.(event, listener);
};
}
return () => undefined;
if (socket.addEventListener) {
socket.addEventListener(event, listener);
return () => socket.removeEventListener?.(event, listener);
}
if (socket.on) {
socket.on(event, listener);
return () => {
if (socket.off) {
socket.off(event, listener);
} else {
socket.removeListener?.(event, listener);
}
};
}
return () => undefined;
}
export function unwrapMessagePayload(value: unknown): unknown {
if (isJsonObject(value) && 'data' in value) {
return value.data;
}
return value;
if (isJsonObject(value) && 'data' in value) {
return value.data;
}
return value;
}
export function unwrapEventPayload(value: unknown): unknown {
if (isJsonObject(value) && 'error' in value) {
return value.error;
}
return value;
if (isJsonObject(value) && 'error' in value) {
return value.error;
}
return value;
}
export function rawToString(value: unknown): string {
if (typeof value === 'string') return value;
if (value instanceof ArrayBuffer) return new TextDecoder().decode(value);
if (ArrayBuffer.isView(value)) {
return new TextDecoder().decode(value);
}
if (value instanceof Blob) {
throw new Error('Blob WebSocket messages are not supported synchronously');
}
if (value && typeof value === 'object' && 'toString' in value && typeof value.toString === 'function') {
return value.toString();
}
return String(value);
if (typeof value === 'string') {
return value;
}
if (value instanceof ArrayBuffer) {
return new TextDecoder().decode(value);
}
if (ArrayBuffer.isView(value)) {
return new TextDecoder().decode(value);
}
if (value instanceof Blob) {
throw new Error('Blob WebSocket messages are not supported synchronously');
}
if (
value &&
typeof value === 'object' &&
'toString' in value &&
typeof value.toString === 'function'
) {
return value.toString();
}
return String(value);
}
export function closeInfo(args: unknown[]): WebSocketCloseInfo {
const first = args[0];
if (isJsonObject(first)) {
const first = args[0];
if (isJsonObject(first)) {
return {
code: typeof first.code === 'number' ? first.code : undefined,
reason: typeof first.reason === 'string' ? first.reason : undefined,
};
}
return {
code: typeof first.code === 'number' ? first.code : undefined,
reason: typeof first.reason === 'string' ? first.reason : undefined,
code: typeof args[0] === 'number' ? args[0] : undefined,
reason: typeof args[1] === 'string' ? args[1] : undefined,
};
}
return {
code: typeof args[0] === 'number' ? args[0] : undefined,
reason: typeof args[1] === 'string' ? args[1] : undefined,
};
}