@onebots/core 0.5.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/errors.js ADDED
@@ -0,0 +1,257 @@
1
+ /**
2
+ * 错误处理和分类系统
3
+ * 提供统一的错误类型和处理机制
4
+ */
5
+ /**
6
+ * 错误分类枚举
7
+ */
8
+ export var ErrorCategory;
9
+ (function (ErrorCategory) {
10
+ /** 网络相关错误 */
11
+ ErrorCategory["NETWORK"] = "NETWORK";
12
+ /** 配置相关错误 */
13
+ ErrorCategory["CONFIG"] = "CONFIG";
14
+ /** 运行时错误 */
15
+ ErrorCategory["RUNTIME"] = "RUNTIME";
16
+ /** 验证错误 */
17
+ ErrorCategory["VALIDATION"] = "VALIDATION";
18
+ /** 资源错误 */
19
+ ErrorCategory["RESOURCE"] = "RESOURCE";
20
+ /** 协议错误 */
21
+ ErrorCategory["PROTOCOL"] = "PROTOCOL";
22
+ /** 适配器错误 */
23
+ ErrorCategory["ADAPTER"] = "ADAPTER";
24
+ /** 未知错误 */
25
+ ErrorCategory["UNKNOWN"] = "UNKNOWN";
26
+ })(ErrorCategory || (ErrorCategory = {}));
27
+ /**
28
+ * 错误严重程度
29
+ */
30
+ export var ErrorSeverity;
31
+ (function (ErrorSeverity) {
32
+ /** 低 - 可以忽略或自动恢复 */
33
+ ErrorSeverity["LOW"] = "LOW";
34
+ /** 中 - 需要记录但可以继续运行 */
35
+ ErrorSeverity["MEDIUM"] = "MEDIUM";
36
+ /** 高 - 影响功能,需要处理 */
37
+ ErrorSeverity["HIGH"] = "HIGH";
38
+ /** 严重 - 可能导致服务停止 */
39
+ ErrorSeverity["CRITICAL"] = "CRITICAL";
40
+ })(ErrorSeverity || (ErrorSeverity = {}));
41
+ /**
42
+ * 基础错误类
43
+ */
44
+ export class OneBotsError extends Error {
45
+ category;
46
+ severity;
47
+ code;
48
+ context;
49
+ timestamp;
50
+ cause;
51
+ constructor(message, options = {}) {
52
+ super(message);
53
+ this.name = 'OneBotsError';
54
+ this.category = options.category || ErrorCategory.UNKNOWN;
55
+ this.severity = options.severity || ErrorSeverity.MEDIUM;
56
+ this.code = options.code || 'UNKNOWN_ERROR';
57
+ this.context = options.context;
58
+ this.cause = options.cause;
59
+ this.timestamp = new Date();
60
+ // 保持错误堆栈
61
+ if (Error.captureStackTrace) {
62
+ Error.captureStackTrace(this, OneBotsError);
63
+ }
64
+ }
65
+ /**
66
+ * 转换为可序列化的对象
67
+ */
68
+ toJSON() {
69
+ return {
70
+ name: this.name,
71
+ message: this.message,
72
+ category: this.category,
73
+ severity: this.severity,
74
+ code: this.code,
75
+ context: this.context,
76
+ timestamp: this.timestamp.toISOString(),
77
+ stack: this.stack,
78
+ cause: this.cause ? {
79
+ message: this.cause.message,
80
+ stack: this.cause.stack,
81
+ } : undefined,
82
+ };
83
+ }
84
+ /**
85
+ * 转换为字符串
86
+ */
87
+ toString() {
88
+ return `[${this.category}:${this.code}] ${this.message}`;
89
+ }
90
+ }
91
+ /**
92
+ * 网络错误
93
+ */
94
+ export class NetworkError extends OneBotsError {
95
+ constructor(message, options) {
96
+ super(message, {
97
+ category: ErrorCategory.NETWORK,
98
+ severity: ErrorSeverity.MEDIUM,
99
+ code: 'NETWORK_ERROR',
100
+ ...options,
101
+ });
102
+ this.name = 'NetworkError';
103
+ }
104
+ }
105
+ /**
106
+ * 配置错误
107
+ */
108
+ export class ConfigError extends OneBotsError {
109
+ constructor(message, options) {
110
+ super(message, {
111
+ category: ErrorCategory.CONFIG,
112
+ severity: ErrorSeverity.HIGH,
113
+ code: 'CONFIG_ERROR',
114
+ ...options,
115
+ });
116
+ this.name = 'ConfigError';
117
+ }
118
+ }
119
+ /**
120
+ * 验证错误
121
+ */
122
+ export class ValidationError extends OneBotsError {
123
+ constructor(message, options) {
124
+ super(message, {
125
+ category: ErrorCategory.VALIDATION,
126
+ severity: ErrorSeverity.MEDIUM,
127
+ code: 'VALIDATION_ERROR',
128
+ ...options,
129
+ });
130
+ this.name = 'ValidationError';
131
+ }
132
+ }
133
+ /**
134
+ * 资源错误
135
+ */
136
+ export class ResourceError extends OneBotsError {
137
+ constructor(message, options) {
138
+ super(message, {
139
+ category: ErrorCategory.RESOURCE,
140
+ severity: ErrorSeverity.HIGH,
141
+ code: 'RESOURCE_ERROR',
142
+ ...options,
143
+ });
144
+ this.name = 'ResourceError';
145
+ }
146
+ }
147
+ /**
148
+ * 协议错误
149
+ */
150
+ export class ProtocolError extends OneBotsError {
151
+ constructor(message, options) {
152
+ super(message, {
153
+ category: ErrorCategory.PROTOCOL,
154
+ severity: ErrorSeverity.MEDIUM,
155
+ code: 'PROTOCOL_ERROR',
156
+ ...options,
157
+ });
158
+ this.name = 'ProtocolError';
159
+ }
160
+ }
161
+ /**
162
+ * 适配器错误
163
+ */
164
+ export class AdapterError extends OneBotsError {
165
+ constructor(message, options) {
166
+ super(message, {
167
+ category: ErrorCategory.ADAPTER,
168
+ severity: ErrorSeverity.HIGH,
169
+ code: 'ADAPTER_ERROR',
170
+ ...options,
171
+ });
172
+ this.name = 'AdapterError';
173
+ }
174
+ }
175
+ /**
176
+ * 运行时错误
177
+ */
178
+ export class RuntimeError extends OneBotsError {
179
+ constructor(message, options) {
180
+ super(message, {
181
+ category: ErrorCategory.RUNTIME,
182
+ severity: ErrorSeverity.HIGH,
183
+ code: 'RUNTIME_ERROR',
184
+ ...options,
185
+ });
186
+ this.name = 'RuntimeError';
187
+ }
188
+ }
189
+ /**
190
+ * 错误处理工具函数
191
+ */
192
+ export class ErrorHandler {
193
+ /**
194
+ * 包装错误,转换为 OneBotsError
195
+ */
196
+ static wrap(error, context) {
197
+ if (error instanceof OneBotsError) {
198
+ if (context) {
199
+ return new OneBotsError(error.message, {
200
+ category: error.category,
201
+ severity: error.severity,
202
+ code: error.code,
203
+ context: { ...error.context, ...context },
204
+ cause: error.cause || error,
205
+ });
206
+ }
207
+ return error;
208
+ }
209
+ if (error instanceof Error) {
210
+ // 尝试从错误消息推断错误类型
211
+ const message = error.message.toLowerCase();
212
+ let category = ErrorCategory.UNKNOWN;
213
+ let code = 'UNKNOWN_ERROR';
214
+ if (message.includes('network') || message.includes('connection') || message.includes('timeout')) {
215
+ category = ErrorCategory.NETWORK;
216
+ code = 'NETWORK_ERROR';
217
+ }
218
+ else if (message.includes('config') || message.includes('configuration')) {
219
+ category = ErrorCategory.CONFIG;
220
+ code = 'CONFIG_ERROR';
221
+ }
222
+ else if (message.includes('validation') || message.includes('invalid')) {
223
+ category = ErrorCategory.VALIDATION;
224
+ code = 'VALIDATION_ERROR';
225
+ }
226
+ else if (message.includes('not found') || message.includes('missing')) {
227
+ category = ErrorCategory.RESOURCE;
228
+ code = 'RESOURCE_NOT_FOUND';
229
+ }
230
+ return new OneBotsError(error.message, {
231
+ category,
232
+ severity: ErrorSeverity.MEDIUM,
233
+ code,
234
+ context,
235
+ cause: error,
236
+ });
237
+ }
238
+ return new OneBotsError(String(error), {
239
+ category: ErrorCategory.UNKNOWN,
240
+ severity: ErrorSeverity.MEDIUM,
241
+ code: 'UNKNOWN_ERROR',
242
+ context,
243
+ });
244
+ }
245
+ /**
246
+ * 判断错误是否可恢复
247
+ */
248
+ static isRecoverable(error) {
249
+ return error.severity === ErrorSeverity.LOW || error.severity === ErrorSeverity.MEDIUM;
250
+ }
251
+ /**
252
+ * 判断错误是否致命
253
+ */
254
+ static isFatal(error) {
255
+ return error.severity === ErrorSeverity.CRITICAL;
256
+ }
257
+ }
package/lib/index.d.ts CHANGED
@@ -1,13 +1,17 @@
1
- export type {} from 'koa-bodyparser';
2
1
  export * from "./account.js";
3
2
  export * from "./adapter.js";
4
3
  export * from "./base-app.js";
5
- export * from './router.js';
6
- export * from "./types.js";
7
4
  export * from "./router.js";
5
+ export * from "./types.js";
8
6
  export * from "./utils.js";
9
7
  export * from "./message-utils.js";
10
8
  export * from "./protocol.js";
11
9
  export * from "./registry.js";
12
- export * from "./registry.js";
13
10
  export * from "./db.js";
11
+ export * from "./errors.js";
12
+ export * from "./logger.js";
13
+ export * from "./config-validator.js";
14
+ export * from "./di-container.js";
15
+ export * from "./lifecycle.js";
16
+ export * from "./retry.js";
17
+ export * from "./rate-limiter.js";
package/lib/index.js CHANGED
@@ -1,12 +1,20 @@
1
+ // Core modules
1
2
  export * from "./account.js";
2
3
  export * from "./adapter.js";
3
4
  export * from "./base-app.js";
4
- export * from './router.js';
5
- export * from "./types.js";
6
5
  export * from "./router.js";
6
+ export * from "./types.js";
7
7
  export * from "./utils.js";
8
8
  export * from "./message-utils.js";
9
9
  export * from "./protocol.js";
10
10
  export * from "./registry.js";
11
- export * from "./registry.js";
12
11
  export * from "./db.js";
12
+ // Enhanced modules
13
+ export * from "./errors.js";
14
+ export * from "./logger.js";
15
+ export * from "./config-validator.js";
16
+ export * from "./di-container.js";
17
+ export * from "./lifecycle.js";
18
+ // Utilities
19
+ export * from "./retry.js";
20
+ export * from "./rate-limiter.js";
@@ -0,0 +1,75 @@
1
+ /**
2
+ * 生命周期管理
3
+ * 提供资源管理和优雅关闭机制
4
+ */
5
+ import { EventEmitter } from 'events';
6
+ import type { Dispose } from './types.js';
7
+ export interface LifecycleHook {
8
+ /** 初始化钩子 */
9
+ onInit?(): void | Promise<void>;
10
+ /** 启动钩子 */
11
+ onStart?(): void | Promise<void>;
12
+ /** 停止钩子 */
13
+ onStop?(): void | Promise<void>;
14
+ /** 清理钩子 */
15
+ onCleanup?(): void | Promise<void>;
16
+ }
17
+ /**
18
+ * 生命周期管理器
19
+ */
20
+ export declare class LifecycleManager extends EventEmitter {
21
+ private resources;
22
+ private hooks;
23
+ private isShuttingDown;
24
+ private shutdownTimeout;
25
+ /**
26
+ * 注册资源
27
+ */
28
+ register(name: string, dispose: Dispose): void;
29
+ /**
30
+ * 注销资源
31
+ */
32
+ unregister(name: string): boolean;
33
+ /**
34
+ * 注册生命周期钩子
35
+ */
36
+ addHook(hook: LifecycleHook): void;
37
+ /**
38
+ * 移除生命周期钩子
39
+ */
40
+ removeHook(hook: LifecycleHook): void;
41
+ /**
42
+ * 初始化所有钩子
43
+ */
44
+ init(): Promise<void>;
45
+ /**
46
+ * 启动所有钩子
47
+ */
48
+ start(): Promise<void>;
49
+ /**
50
+ * 停止所有钩子
51
+ */
52
+ stop(): Promise<void>;
53
+ /**
54
+ * 清理所有资源
55
+ */
56
+ cleanup(): Promise<void>;
57
+ /**
58
+ * 优雅关闭
59
+ */
60
+ gracefulShutdown(signal?: string, options?: {
61
+ exitOnTimeout?: boolean;
62
+ }): Promise<void>;
63
+ /**
64
+ * 设置关闭超时时间
65
+ */
66
+ setShutdownTimeout(timeout: number): void;
67
+ /**
68
+ * 获取资源数量
69
+ */
70
+ getResourceCount(): number;
71
+ /**
72
+ * 获取所有资源名称
73
+ */
74
+ getResourceNames(): string[];
75
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * 生命周期管理
3
+ * 提供资源管理和优雅关闭机制
4
+ */
5
+ import { EventEmitter } from 'events';
6
+ import { ResourceError } from './errors.js';
7
+ /**
8
+ * 生命周期管理器
9
+ */
10
+ export class LifecycleManager extends EventEmitter {
11
+ resources = new Map();
12
+ hooks = [];
13
+ isShuttingDown = false;
14
+ shutdownTimeout = 30000; // 30秒超时
15
+ /**
16
+ * 注册资源
17
+ */
18
+ register(name, dispose) {
19
+ if (this.resources.has(name)) {
20
+ throw new ResourceError(`Resource ${name} already registered`);
21
+ }
22
+ this.resources.set(name, dispose);
23
+ }
24
+ /**
25
+ * 注销资源
26
+ */
27
+ unregister(name) {
28
+ return this.resources.delete(name);
29
+ }
30
+ /**
31
+ * 注册生命周期钩子
32
+ */
33
+ addHook(hook) {
34
+ this.hooks.push(hook);
35
+ }
36
+ /**
37
+ * 移除生命周期钩子
38
+ */
39
+ removeHook(hook) {
40
+ const index = this.hooks.indexOf(hook);
41
+ if (index !== -1) {
42
+ this.hooks.splice(index, 1);
43
+ }
44
+ }
45
+ /**
46
+ * 初始化所有钩子
47
+ */
48
+ async init() {
49
+ this.emit('beforeInit');
50
+ for (const hook of this.hooks) {
51
+ if (hook.onInit) {
52
+ await hook.onInit();
53
+ }
54
+ }
55
+ this.emit('afterInit');
56
+ }
57
+ /**
58
+ * 启动所有钩子
59
+ */
60
+ async start() {
61
+ this.emit('beforeStart');
62
+ for (const hook of this.hooks) {
63
+ if (hook.onStart) {
64
+ await hook.onStart();
65
+ }
66
+ }
67
+ this.emit('afterStart');
68
+ }
69
+ /**
70
+ * 停止所有钩子
71
+ */
72
+ async stop() {
73
+ this.emit('beforeStop');
74
+ for (const hook of this.hooks) {
75
+ if (hook.onStop) {
76
+ await hook.onStop();
77
+ }
78
+ }
79
+ this.emit('afterStop');
80
+ }
81
+ /**
82
+ * 清理所有资源
83
+ */
84
+ async cleanup() {
85
+ if (this.isShuttingDown) {
86
+ return;
87
+ }
88
+ this.isShuttingDown = true;
89
+ this.emit('beforeCleanup');
90
+ // 执行清理钩子
91
+ for (const hook of this.hooks) {
92
+ if (hook.onCleanup) {
93
+ try {
94
+ await hook.onCleanup();
95
+ }
96
+ catch (error) {
97
+ this.emit('cleanupError', { hook: 'onCleanup', error });
98
+ // 继续执行,不抛出错误
99
+ }
100
+ }
101
+ }
102
+ // 清理所有资源
103
+ const cleanupPromises = [];
104
+ for (const [name, dispose] of this.resources.entries()) {
105
+ cleanupPromises.push((async () => {
106
+ try {
107
+ const result = dispose();
108
+ if (result instanceof Promise) {
109
+ await result;
110
+ }
111
+ }
112
+ catch (error) {
113
+ this.emit('cleanupError', { name, error });
114
+ // 继续执行,不抛出错误
115
+ }
116
+ })());
117
+ }
118
+ await Promise.all(cleanupPromises);
119
+ this.resources.clear();
120
+ this.hooks = [];
121
+ this.emit('afterCleanup');
122
+ }
123
+ /**
124
+ * 优雅关闭
125
+ */
126
+ async gracefulShutdown(signal, options) {
127
+ if (this.isShuttingDown) {
128
+ return;
129
+ }
130
+ this.emit('shutdown', signal);
131
+ // 设置超时
132
+ let timeout = null;
133
+ if (this.shutdownTimeout > 0) {
134
+ timeout = setTimeout(() => {
135
+ this.emit('shutdownTimeout');
136
+ if (options?.exitOnTimeout !== false) {
137
+ process.exit(1);
138
+ }
139
+ }, this.shutdownTimeout);
140
+ }
141
+ try {
142
+ await this.stop();
143
+ await this.cleanup();
144
+ if (timeout) {
145
+ clearTimeout(timeout);
146
+ }
147
+ this.emit('shutdownComplete');
148
+ }
149
+ catch (error) {
150
+ if (timeout) {
151
+ clearTimeout(timeout);
152
+ }
153
+ this.emit('shutdownError', error);
154
+ throw error;
155
+ }
156
+ }
157
+ /**
158
+ * 设置关闭超时时间
159
+ */
160
+ setShutdownTimeout(timeout) {
161
+ this.shutdownTimeout = timeout;
162
+ }
163
+ /**
164
+ * 获取资源数量
165
+ */
166
+ getResourceCount() {
167
+ return this.resources.size;
168
+ }
169
+ /**
170
+ * 获取所有资源名称
171
+ */
172
+ getResourceNames() {
173
+ return Array.from(this.resources.keys());
174
+ }
175
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * 增强的日志系统
3
+ * 提供结构化日志、错误追踪和上下文信息
4
+ */
5
+ import { OneBotsError } from './errors.js';
6
+ import type { LogLevel } from './types.js';
7
+ export interface LogContext {
8
+ [key: string]: any;
9
+ }
10
+ export interface LogEntry {
11
+ level: string;
12
+ message: string;
13
+ context?: LogContext;
14
+ error?: OneBotsError;
15
+ timestamp: Date;
16
+ }
17
+ /**
18
+ * 增强的 Logger 类
19
+ */
20
+ export declare class Logger {
21
+ private logger;
22
+ private context;
23
+ constructor(name: string, level?: LogLevel);
24
+ /**
25
+ * 设置日志级别
26
+ */
27
+ setLevel(level: LogLevel): void;
28
+ /**
29
+ * 添加上下文信息
30
+ */
31
+ withContext(context: LogContext): Logger;
32
+ /**
33
+ * Trace 级别日志
34
+ */
35
+ trace(message: string, context?: LogContext): void;
36
+ /**
37
+ * Debug 级别日志
38
+ */
39
+ debug(message: string, context?: LogContext): void;
40
+ /**
41
+ * Info 级别日志
42
+ */
43
+ info(message: string, context?: LogContext): void;
44
+ /**
45
+ * Warn 级别日志
46
+ */
47
+ warn(message: string, context?: LogContext): void;
48
+ /**
49
+ * Error 级别日志
50
+ */
51
+ error(message: string | Error | OneBotsError, context?: LogContext): void;
52
+ /**
53
+ * Fatal 级别日志
54
+ */
55
+ fatal(message: string | Error | OneBotsError, context?: LogContext): void;
56
+ /**
57
+ * Mark 级别日志
58
+ */
59
+ mark(message: string, context?: LogContext): void;
60
+ /**
61
+ * 记录性能指标
62
+ */
63
+ performance(operation: string, duration: number, context?: LogContext): void;
64
+ /**
65
+ * 记录操作开始
66
+ */
67
+ start(operation: string, context?: LogContext): () => void;
68
+ /**
69
+ * 内部日志方法
70
+ */
71
+ private log;
72
+ }
73
+ /**
74
+ * 创建 Logger 实例
75
+ */
76
+ export declare function createLogger(name: string, level?: LogLevel): Logger;