@yumerijs/core 3.0.6 → 3.1.5

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/dist/config.d.ts CHANGED
@@ -1,5 +1,14 @@
1
1
  import type { I18n } from './i18n.js';
2
+ /**
3
+ * 根据 schema 的定义,为配置项提供默认值
4
+ * @param schema schema 定义
5
+ * @param config 当前配置
6
+ * @returns 填充默认值后的配置
7
+ */
2
8
  export declare function fallback<T>(schema: Schema<T>, config: T): T;
9
+ /**
10
+ * 配置 schema 类
11
+ */
3
12
  export declare class Schema<T = any> {
4
13
  _type?: T;
5
14
  type: string;
@@ -14,17 +23,62 @@ export declare class Schema<T = any> {
14
23
  constructor(definition: Omit<Schema<T>, '_type' | 'required' | 'default' | 'key'> & {
15
24
  enum?: T[];
16
25
  });
26
+ /**
27
+ * 创建一个字符串类型的配置 schema
28
+ * @param description 说明文字
29
+ * @returns 字符串类型的配置 schema
30
+ */
17
31
  static string(description?: string): Schema<string>;
32
+ /**
33
+ * 创建一个数字类型的配置 schema
34
+ * @param description 说明文字
35
+ * @returns 数字类型的配置 schema
36
+ */
18
37
  static number(description?: string): Schema<number>;
38
+ /**
39
+ * 创建一个布尔类型的配置 schema
40
+ * @param description 说明文字
41
+ * @returns 布尔类型的配置 schema
42
+ */
19
43
  static boolean(description?: string): Schema<boolean>;
44
+ /**
45
+ * 创建一个数组类型的配置 schema
46
+ * @param inner 数组元素的 schema
47
+ * @param description 说明文字
48
+ * @returns 数组类型的配置 schema
49
+ */
20
50
  static array<T>(inner: Schema<T>, description?: string): Schema<T[]>;
51
+ /**
52
+ * 创建一个对象类型的配置 schema
53
+ * @param properties 对象的属性 schema
54
+ * @param description 说明文字
55
+ * @returns 对象类型的配置 schema
56
+ */
21
57
  static object<T extends {}>(properties: {
22
58
  [K in keyof T]: Schema<T[K]>;
23
59
  }, description?: string): Schema<T>;
60
+ /**
61
+ * 创建一个扩展的对象类型的配置 schema
62
+ * @param base 基础对象的 schema
63
+ * @param extension 扩展属性的 schema
64
+ * @param description 说明文字
65
+ * @returns 扩展的对象类型的配置 schema
66
+ */
24
67
  static extend<T extends {}, U extends {}>(base: Schema<T>, extension: {
25
68
  [K in keyof U]: Schema<U[K]>;
26
69
  }, description?: string): Schema<T & U>;
70
+ /**
71
+ * 创建一个枚举类型的配置 schema
72
+ * @param values 枚举值列表
73
+ * @param description 说明文字
74
+ * @returns 枚举类型的配置 schema
75
+ */
27
76
  static enum<L extends string | number>(values: L[], description?: string): Schema<L>;
77
+ /**
78
+ * 将配置项标记为必填
79
+ * @param this
80
+ * @returns
81
+ */
28
82
  required(this: this): this;
29
83
  /**
30
84
  * 绑定说明文字的 i18n key
package/dist/config.js CHANGED
@@ -1,6 +1,12 @@
1
1
  function isNullable(value) {
2
2
  return value === null || value === undefined;
3
3
  }
4
+ /**
5
+ * 根据 schema 的定义,为配置项提供默认值
6
+ * @param schema schema 定义
7
+ * @param config 当前配置
8
+ * @returns 填充默认值后的配置
9
+ */
4
10
  export function fallback(schema, config) {
5
11
  if (!schema)
6
12
  return config;
@@ -25,6 +31,9 @@ export function fallback(schema, config) {
25
31
  }
26
32
  return result;
27
33
  }
34
+ /**
35
+ * 配置 schema 类
36
+ */
28
37
  export class Schema {
29
38
  _type; // Phantom type
30
39
  type;
@@ -46,29 +55,74 @@ export class Schema {
46
55
  this.items = definition.items;
47
56
  this.enum = definition.enum;
48
57
  }
58
+ /**
59
+ * 创建一个字符串类型的配置 schema
60
+ * @param description 说明文字
61
+ * @returns 字符串类型的配置 schema
62
+ */
49
63
  static string(description) {
50
64
  return new Schema({ type: 'string', description });
51
65
  }
66
+ /**
67
+ * 创建一个数字类型的配置 schema
68
+ * @param description 说明文字
69
+ * @returns 数字类型的配置 schema
70
+ */
52
71
  static number(description) {
53
72
  return new Schema({ type: 'number', description });
54
73
  }
74
+ /**
75
+ * 创建一个布尔类型的配置 schema
76
+ * @param description 说明文字
77
+ * @returns 布尔类型的配置 schema
78
+ */
55
79
  static boolean(description) {
56
80
  return new Schema({ type: 'boolean', description });
57
81
  }
82
+ /**
83
+ * 创建一个数组类型的配置 schema
84
+ * @param inner 数组元素的 schema
85
+ * @param description 说明文字
86
+ * @returns 数组类型的配置 schema
87
+ */
58
88
  static array(inner, description) {
59
89
  return new Schema({ type: 'array', items: inner, description });
60
90
  }
91
+ /**
92
+ * 创建一个对象类型的配置 schema
93
+ * @param properties 对象的属性 schema
94
+ * @param description 说明文字
95
+ * @returns 对象类型的配置 schema
96
+ */
61
97
  static object(properties, description) {
62
98
  return new Schema({ type: 'object', properties, description });
63
99
  }
100
+ /**
101
+ * 创建一个扩展的对象类型的配置 schema
102
+ * @param base 基础对象的 schema
103
+ * @param extension 扩展属性的 schema
104
+ * @param description 说明文字
105
+ * @returns 扩展的对象类型的配置 schema
106
+ */
64
107
  static extend(base, extension, description) {
65
108
  const combinedProperties = { ...base.properties, ...extension };
66
109
  return new Schema({ type: 'object', properties: combinedProperties, description: description || base.description });
67
110
  }
111
+ /**
112
+ * 创建一个枚举类型的配置 schema
113
+ * @param values 枚举值列表
114
+ * @param description 说明文字
115
+ * @returns 枚举类型的配置 schema
116
+ */
68
117
  static enum(values, description) {
69
118
  const type = typeof values[0] === 'string' ? 'string' : typeof values[0] === 'number' ? 'number' : 'string'; // Infer type based on first value
70
119
  return new Schema({ type, enum: values, description });
71
120
  }
121
+ /**
122
+ * 将配置项标记为必填
123
+ * @param this
124
+ * @returns
125
+ */
72
126
  required() {
73
127
  this.isRequired = true;
74
128
  return this;
package/dist/context.d.ts CHANGED
File without changes
package/dist/context.js CHANGED
@@ -372,16 +372,15 @@ export class Context {
372
372
  this.core.unhook(hook, hookname);
373
373
  });
374
374
  }
375
- // 卸载子插件(异步即可,不必按顺序)
376
- this.childPlugins.forEach(async (plugin, ctx) => {
375
+ // 卸载子插件
376
+ for (const [ctx, plugin] of this.childPlugins) {
377
377
  if (plugin?.disable)
378
378
  await plugin.disable(ctx);
379
- });
379
+ }
380
380
  // 删除子上下文
381
- this.childContexts.forEach((ctx) => {
382
- if (ctx?.dispose)
383
- ctx.dispose();
384
- });
381
+ for (const ctx of this.childContexts) {
382
+ await ctx.dispose();
383
+ }
385
384
  // 删除i18n
386
385
  if (this.i18ns?.length) {
387
386
  for (const key of this.i18ns) {
package/dist/core.d.ts CHANGED
@@ -74,7 +74,8 @@ export declare const enum PluginStatus {
74
74
  PENDING = "pending"
75
75
  }
76
76
  export declare class Core {
77
- emitter: EventEmitter<[never]>;
77
+ emitter: EventEmitter<any>;
78
+ private eventListeners;
78
79
  components: {
79
80
  [name: string]: any;
80
81
  };
@@ -105,12 +106,26 @@ export declare class Core {
105
106
  setI18n(i18n: I18n): void;
106
107
  constructor(loader?: any, coreConfig?: CoreOptions, loggersetCore?: boolean, splash?: boolean);
107
108
  private checkUpdate;
109
+ /**
110
+ * 添加渲染器
111
+ * @param renderer 渲染器实例
112
+ */
108
113
  addRenderer(renderer: IRenderer): void;
114
+ /**
115
+ * 设置存储实例
116
+ * @param storage 存储实例
117
+ */
109
118
  setStorage(storage: SessionStorageProcessor | Storage<SessionStorageSnapshot>): void;
110
119
  getStorage(): SessionStorageProcessor;
111
120
  getRendererForPlugin(pluginName: string): string | undefined;
112
121
  runCore(): Promise<void>;
113
122
  getShortPluginName(pluginName: string): string;
123
+ /**
124
+ * 应用插件
125
+ * @param module 插件模块
126
+ * @param context 上下文
127
+ * @param config 配置
128
+ */
114
129
  plugin(module: PluginModuleLike, context: Context, config: Config): Promise<void>;
115
130
  registerComponent(name: string, component: any): void;
116
131
  getComponent(name: string): any;
@@ -118,14 +133,60 @@ export declare class Core {
118
133
  registerService(name: string, service: new (context: Context) => Service): void;
119
134
  getService(name: string, context: Context): Service | undefined;
120
135
  unregisterService(name: string): void;
136
+ /**
137
+ * 添加事件监听器
138
+ * @param event 事件名称
139
+ * @param listener 监听器函数
140
+ */
121
141
  on(event: string, listener: (...args: any[]) => Promise<void>): void;
142
+ /**
143
+ * 触发事件
144
+ * @param event 事件名称
145
+ * @param payload 事件载荷
146
+ */
122
147
  emit(event: string, ...payload: any): void;
123
148
  off(event: string, listener: (...args: any[]) => Promise<void>): void;
149
+ /**
150
+ * 注册全局中间件
151
+ * @param name 中间件名称
152
+ * @param middleware 中间件函数
153
+ * @returns
154
+ */
124
155
  use(name: string, middleware: Middleware): Core;
156
+ /**
157
+ * 注册路由
158
+ * @param path 路由路径
159
+ * @param context 上下文
160
+ * @returns 路由实例
161
+ */
125
162
  route(path: string, context: Context): Route;
163
+ /**
164
+ * 注册钩子
165
+ * @param name 钩子名称
166
+ * @param hookname 钩子函数名称
167
+ * @param callback 钩子函数
168
+ */
126
169
  hook(name: string, hookname: string, callback: HookHandler): any;
170
+ /**
171
+ * 注销钩子
172
+ * @param name 钩子名称
173
+ * @param hookname 钩子函数名称
174
+ */
127
175
  unhook(name: string, hookname: string): any;
176
+ /**
177
+ * 执行钩子
178
+ * @param name 钩子名称
179
+ * @param args 钩子参数
180
+ * @returns 钩子执行结果
181
+ */
128
182
  hookExecute(name: string, ...args: any[]): Promise<any[]>;
183
+ /**
184
+ * 执行路由
185
+ * @param pathname 路由路径
186
+ * @param session 会话
187
+ * @param queryParams 查询参数
188
+ * @returns
189
+ */
129
190
  executeRoute(pathname: string, session: Session, queryParams: URLSearchParams): Promise<boolean>;
130
191
  getRoute(path: string): Route | false;
131
192
  }
package/dist/core.js CHANGED
@@ -72,6 +72,7 @@ export const coreI18n = {
72
72
  };
73
73
  export class Core {
74
74
  emitter = new EventEmitter();
75
+ eventListeners = new Map();
75
76
  components = {};
76
77
  services = {};
77
78
  routes = {};
@@ -134,12 +135,20 @@ export class Core {
134
135
  this.logger.error('Error while checking updates: ', error.message);
135
136
  }
136
137
  }
138
+ /**
139
+ * 添加渲染器
140
+ * @param renderer 渲染器实例
141
+ */
137
142
  addRenderer(renderer) {
138
143
  if (this.renderers.has(renderer.name)) {
139
144
  this.logger.warn(`Renderer "${renderer.name}" is already registered and will be overwritten.`);
140
145
  }
141
146
  this.renderers.set(renderer.name, renderer);
142
147
  }
148
+ /**
149
+ * 设置存储实例
150
+ * @param storage 存储实例
151
+ */
143
152
  setStorage(storage) {
144
153
  if (storage instanceof SessionStorageProcessor) {
145
154
  this.storage = storage;
@@ -173,6 +182,12 @@ export class Core {
173
182
  }
174
183
  return pluginName;
175
184
  }
185
+ /**
186
+ * 应用插件
187
+ * @param module 插件模块
188
+ * @param context 上下文
189
+ * @param config 配置
190
+ */
176
191
  async plugin(module, context, config) {
177
192
  const plugin = resolvePluginModule(module, context, config);
178
193
  const shortName = this.getShortPluginName(context.pluginname);
@@ -213,49 +228,107 @@ export class Core {
213
228
  unregisterService(name) {
214
229
  delete this.services[name];
215
230
  }
231
+ /**
232
+ * 添加事件监听器
233
+ * @param event 事件名称
234
+ * @param listener 监听器函数
235
+ */
216
236
  on(event, listener) {
217
- this.emitter.on(event, (...args) => {
237
+ const wrapped = (...args) => {
218
238
  // 包一层保证 async 可以被捕获
219
239
  Promise.resolve(listener(...args)).catch((err) => {
220
240
  console.error(`Error in event listener for "${event}":`, err);
221
241
  });
222
- });
242
+ };
243
+ this.emitter.on(event, wrapped);
244
+ const listeners = this.eventListeners.get(event) || [];
245
+ listeners.push({ listener, wrapped });
246
+ this.eventListeners.set(event, listeners);
223
247
  }
248
+ /**
249
+ * 触发事件
250
+ * @param event 事件名称
251
+ * @param payload 事件载荷
252
+ */
224
253
  emit(event, ...payload) {
225
254
  this.emitter.emit(event, ...payload);
226
255
  }
227
256
  // 删除监听器
228
257
  off(event, listener) {
229
- // 原生 EventEmitter 必须删“同一个函数引用”
230
- // 所以必须包装一致,这里我们直接用 listener 本体删
231
- this.emitter.off(event, listener);
258
+ const listeners = this.eventListeners.get(event);
259
+ if (!listeners)
260
+ return;
261
+ const index = listeners.findIndex(item => item.listener === listener);
262
+ if (index === -1)
263
+ return;
264
+ const [{ wrapped }] = listeners.splice(index, 1);
265
+ this.emitter.off(event, wrapped);
266
+ if (listeners.length === 0) {
267
+ this.eventListeners.delete(event);
268
+ }
232
269
  }
270
+ /**
271
+ * 注册全局中间件
272
+ * @param name 中间件名称
273
+ * @param middleware 中间件函数
274
+ * @returns
275
+ */
233
276
  use(name, middleware) {
234
277
  this.globalMiddlewares[name] = middleware;
235
278
  return this;
236
279
  }
280
+ /**
281
+ * 注册路由
282
+ * @param path 路由路径
283
+ * @param context 上下文
284
+ * @returns 路由实例
285
+ */
237
286
  route(path, context) {
238
287
  const route = new Route(path, context);
239
288
  this.routes[path] = route;
240
289
  return route;
241
290
  }
291
+ /**
292
+ * 注册钩子
293
+ * @param name 钩子名称
294
+ * @param hookname 钩子函数名称
295
+ * @param callback 钩子函数
296
+ */
242
297
  hook(name, hookname, callback) {
243
298
  if (!this.hooks[name]) {
244
299
  this.hooks[name] = new Hook(name);
245
300
  }
246
301
  this.hooks[name].add(hookname, callback);
247
302
  }
303
+ /**
304
+ * 注销钩子
305
+ * @param name 钩子名称
306
+ * @param hookname 钩子函数名称
307
+ */
248
308
  unhook(name, hookname) {
249
309
  if (this.hooks[name]) {
250
310
  this.hooks[name].remove(hookname);
251
311
  }
252
312
  }
313
+ /**
314
+ * 执行钩子
315
+ * @param name 钩子名称
316
+ * @param args 钩子参数
317
+ * @returns 钩子执行结果
318
+ */
253
319
  async hookExecute(name, ...args) {
254
320
  if (this.hooks[name]) {
255
321
  return await this.hooks[name].trigger(...args);
256
322
  }
257
323
  return [];
258
324
  }
325
+ /**
326
+ * 执行路由
327
+ * @param pathname 路由路径
328
+ * @param session 会话
329
+ * @param queryParams 查询参数
330
+ * @returns
331
+ */
259
332
  async executeRoute(pathname, session, queryParams) {
260
333
  for (const routePath in this.routes) {
261
334
  const route = this.routes[routePath];
@@ -266,12 +339,13 @@ export class Core {
266
339
  continue;
267
340
  }
268
341
  try {
342
+ const requestStart = Date.now();
269
343
  this.emit('request:start', {
270
344
  path: pathname,
271
345
  route: routePath,
272
346
  method: session?.client?.req?.method,
273
347
  plugin: route.context?.pluginname,
274
- start: Date.now(),
348
+ start: requestStart,
275
349
  sessionId: session?.sessionid,
276
350
  });
277
351
  const middlewares = [...Object.values(this.globalMiddlewares), ...(route.middlewares || [])];
@@ -308,7 +382,7 @@ export class Core {
308
382
  route: routePath,
309
383
  method: session?.client?.req?.method,
310
384
  plugin: route.context?.pluginname,
311
- duration: Date.now() - session._startAt || undefined,
385
+ duration: Date.now() - requestStart,
312
386
  status: session?.status,
313
387
  sessionId: session?.sessionid,
314
388
  });
@@ -0,0 +1,34 @@
1
+ export declare class AppError extends Error {
2
+ errorCode: string;
3
+ statusCode: number;
4
+ details?: any;
5
+ message: string;
6
+ constructor(errorCode: string, statusCode: number, message: string, details?: any);
7
+ }
8
+ export declare class NotFoundError extends AppError {
9
+ constructor(message: string, details?: any);
10
+ }
11
+ export declare class ValidationError extends AppError {
12
+ constructor(message: string, details?: any);
13
+ }
14
+ export declare class UnauthorizedError extends AppError {
15
+ constructor(message: string, details?: any);
16
+ }
17
+ export declare class ForbiddenError extends AppError {
18
+ constructor(message: string, details?: any);
19
+ }
20
+ export declare class InternalServerError extends AppError {
21
+ constructor(message: string, details?: any);
22
+ }
23
+ export declare class BadRequestError extends AppError {
24
+ constructor(message: string, details?: any);
25
+ }
26
+ export declare class UpstreamError extends AppError {
27
+ constructor(message: string, details?: any);
28
+ }
29
+ export declare class UpstreamTimeoutError extends AppError {
30
+ constructor(message: string, details?: any);
31
+ }
32
+ export declare class TooManyRequestsError extends AppError {
33
+ constructor(message: string, details?: any);
34
+ }
package/dist/error.js ADDED
@@ -0,0 +1,58 @@
1
+ export class AppError extends Error {
2
+ errorCode;
3
+ statusCode;
4
+ details;
5
+ message;
6
+ constructor(errorCode, statusCode, message, details) {
7
+ super(message);
8
+ this.errorCode = errorCode;
9
+ this.statusCode = statusCode;
10
+ this.message = message;
11
+ this.details = details;
12
+ }
13
+ }
14
+ export class NotFoundError extends AppError {
15
+ constructor(message, details) {
16
+ super('NOT_FOUND', 404, message, details);
17
+ }
18
+ }
19
+ export class ValidationError extends AppError {
20
+ constructor(message, details) {
21
+ super('VALIDATION_ERROR', 400, message, details);
22
+ }
23
+ }
24
+ export class UnauthorizedError extends AppError {
25
+ constructor(message, details) {
26
+ super('UNAUTHORIZED', 401, message, details);
27
+ }
28
+ }
29
+ export class ForbiddenError extends AppError {
30
+ constructor(message, details) {
31
+ super('FORBIDDEN', 403, message, details);
32
+ }
33
+ }
34
+ export class InternalServerError extends AppError {
35
+ constructor(message, details) {
36
+ super('INTERNAL_SERVER_ERROR', 500, message, details);
37
+ }
38
+ }
39
+ export class BadRequestError extends AppError {
40
+ constructor(message, details) {
41
+ super('BAD_REQUEST', 400, message, details);
42
+ }
43
+ }
44
+ export class UpstreamError extends AppError {
45
+ constructor(message, details) {
46
+ super('UPSTREAM_ERROR', 502, message, details);
47
+ }
48
+ }
49
+ export class UpstreamTimeoutError extends AppError {
50
+ constructor(message, details) {
51
+ super('UPSTREAM_TIMEOUT', 504, message, details);
52
+ }
53
+ }
54
+ export class TooManyRequestsError extends AppError {
55
+ constructor(message, details) {
56
+ super('TOO_MANY_REQUESTS', 429, message, details);
57
+ }
58
+ }
package/dist/hook.d.ts CHANGED
File without changes
package/dist/hook.js CHANGED
File without changes
package/dist/i18n.d.ts CHANGED
@@ -8,7 +8,16 @@ export declare class I18n {
8
8
  private data;
9
9
  private fallback;
10
10
  constructor(fallback?: string[]);
11
+ /**
12
+ * 注册翻译文本
13
+ * @param key 文本点
14
+ * @param lang 语言映射
15
+ */
11
16
  register(key: string | Record<string, any>, lang?: Record<string, string>): void;
17
+ /**
18
+ * 设置回退语言
19
+ * @param fallback 回退语言数组
20
+ */
12
21
  setFallback(fallback: string[]): void;
13
22
  /**
14
23
  * 判断一个值是否是语言表,即 `{ zh: '...', en: '...' }` 这种值全为字符串的对象。
package/dist/i18n.js CHANGED
@@ -9,6 +9,11 @@ export class I18n {
9
9
  constructor(fallback = ['en']) {
10
10
  this.fallback = fallback;
11
11
  }
12
+ /**
13
+ * 注册翻译文本
14
+ * @param key 文本点
15
+ * @param lang 语言映射
16
+ */
12
17
  register(key, lang) {
13
18
  if (typeof key === 'string' && lang) {
14
19
  if (!this.data[key])
@@ -19,6 +24,10 @@ export class I18n {
19
24
  this.flattenAndRegister(key);
20
25
  }
21
26
  }
27
+ /**
28
+ * 设置回退语言
29
+ * @param fallback 回退语言数组
30
+ */
22
31
  setFallback(fallback) {
23
32
  this.fallback = fallback;
24
33
  }
package/dist/index.d.ts CHANGED
@@ -14,3 +14,4 @@ export * from './middleware.js';
14
14
  export * from './i18n.js';
15
15
  export * from './storage.js';
16
16
  export * from './service.js';
17
+ export * from './error.js';
package/dist/index.js CHANGED
@@ -14,3 +14,4 @@ export * from './middleware.js';
14
14
  export * from './i18n.js';
15
15
  export * from './storage.js';
16
16
  export * from './service.js';
17
+ export * from './error.js';
package/dist/logger.d.ts CHANGED
@@ -21,9 +21,32 @@ export declare class Logger {
21
21
  private getColorByName;
22
22
  private getTimestamp;
23
23
  private log;
24
+ /**
25
+ * 记录调试信息
26
+ * @param args 调试信息
27
+ */
24
28
  debug(...args: any[]): void;
29
+ /**
30
+ * 记录信息
31
+ * @param args 信息内容
32
+ */
25
33
  info(...args: any[]): void;
34
+ /**
35
+ * 记录警告信息
36
+ * @param args 警告信息
37
+ */
26
38
  warn(...args: any[]): void;
39
+ /**
40
+ * 记录错误信息
41
+ * @param args 错误信息
42
+ */
27
43
  error(...args: any[]): void;
44
+ /**
45
+ * Display an interactive prompt and resolve with the entered text.
46
+ * The answer is deliberately not added to the log stream because it may be sensitive.
47
+ */
48
+ input(question: string): Promise<string>;
49
+ /** Alias for input(), for callers that prefer prompt terminology. */
50
+ prompt(question: string): Promise<string>;
28
51
  }
29
52
  export {};
package/dist/logger.js CHANGED
@@ -4,6 +4,8 @@
4
4
  * WindyPear-Team All right reserved
5
5
  **/
6
6
  import * as pcc from 'picocolors';
7
+ import { createInterface } from 'readline/promises';
8
+ import { stdin, stdout } from 'process';
7
9
  const { createColors } = pcc;
8
10
  const pc = createColors();
9
11
  export class Logger {
@@ -52,22 +54,60 @@ export class Logger {
52
54
  Logger.coreInstance?.emit('log', { level, message: args.join(' '), timestamp });
53
55
  Logger.logs.push({ level, message: args.join(' '), timestamp });
54
56
  }
57
+ /**
58
+ * 记录调试信息
59
+ * @param args 调试信息
60
+ */
55
61
  debug(...args) {
56
62
  if (Logger.level === 'debug') {
57
63
  this.log('D', ...args);
58
64
  }
59
65
  }
66
+ /**
67
+ * 记录信息
68
+ * @param args 信息内容
69
+ */
60
70
  info(...args) {
61
71
  if (Logger.level === 'info' || Logger.level === 'debug') {
62
72
  this.log('I', ...args);
63
73
  }
64
74
  }
75
+ /**
76
+ * 记录警告信息
77
+ * @param args 警告信息
78
+ */
65
79
  warn(...args) {
66
80
  if (Logger.level !== 'error') {
67
81
  this.log('W', ...args);
68
82
  }
69
83
  }
84
+ /**
85
+ * 记录错误信息
86
+ * @param args 错误信息
87
+ */
70
88
  error(...args) {
71
89
  this.log('E', ...args);
72
90
  }
91
+ /**
92
+ * Display an interactive prompt and resolve with the entered text.
93
+ * The answer is deliberately not added to the log stream because it may be sensitive.
94
+ */
95
+ async input(question) {
96
+ if (!stdin.isTTY || !stdout.isTTY) {
97
+ throw new Error('Logger input requires an interactive terminal.');
98
+ }
99
+ const readline = createInterface({ input: stdin, output: stdout });
100
+ const timestamp = this.getTimestamp();
101
+ const prefix = `${pc.gray(timestamp)} [${pc.cyan('I')}] ${this.titleColor(this.title)} `;
102
+ try {
103
+ return await readline.question(`${prefix}${question}`);
104
+ }
105
+ finally {
106
+ readline.close();
107
+ }
108
+ }
109
+ /** Alias for input(), for callers that prefer prompt terminology. */
110
+ async prompt(question) {
111
+ return await this.input(question);
112
+ }
73
113
  }
File without changes
File without changes
package/dist/route.d.ts CHANGED
File without changes
package/dist/route.js CHANGED
File without changes
package/dist/server.d.ts CHANGED
@@ -19,6 +19,7 @@ export declare class Server {
19
19
  private port;
20
20
  private host;
21
21
  private enableCors;
22
+ private enableWs;
22
23
  private httpServer;
23
24
  constructor(core: Core, config?: Partial<ServerConfig>);
24
25
  /**
package/dist/server.js CHANGED
@@ -3,6 +3,7 @@ import { Session } from './session.js';
3
3
  import http from 'http';
4
4
  import { URL } from 'url';
5
5
  import { resolveVirtualAsset } from '@yumerijs/types';
6
+ import { AppError } from './error.js';
6
7
  const logger = new Logger('server');
7
8
  /** 判断是否为流对象 */
8
9
  function isStream(value) {
@@ -17,12 +18,14 @@ export class Server {
17
18
  port;
18
19
  host;
19
20
  enableCors;
21
+ enableWs;
20
22
  httpServer = null;
21
23
  constructor(core, config = {}) {
22
24
  this.core = core;
23
25
  this.port = config.port ?? 14510;
24
26
  this.host = config.host ?? '0.0.0.0';
25
27
  this.enableCors = config.enableCors ?? true;
28
+ this.enableWs = config.enableWs ?? false;
26
29
  }
27
30
  /**
28
31
  * 创建一个新的会话对象
@@ -97,6 +100,24 @@ export class Server {
97
100
  try {
98
101
  matched = await this.core.executeRoute(routePath, session, queryParams);
99
102
  }
103
+ catch (err) {
104
+ if (err instanceof AppError) {
105
+ session.status = err.statusCode;
106
+ session.body = {
107
+ error: err.errorCode,
108
+ message: err.message,
109
+ details: err.details,
110
+ };
111
+ }
112
+ else {
113
+ logger.error('Unexpected error during route execution:', err);
114
+ session.status = 500;
115
+ session.body = {
116
+ error: 'INTERNAL_SERVER_ERROR',
117
+ message: 'An unexpected error occurred.',
118
+ };
119
+ }
120
+ }
100
121
  finally {
101
122
  if (matched) {
102
123
  await session.saveData(true);
@@ -132,6 +153,10 @@ export class Server {
132
153
  head['Access-Control-Allow-Origin'] = '*';
133
154
  }
134
155
  res.writeHead(session.status ?? 200, head);
156
+ if (session.body === undefined || session.body === null) {
157
+ res.end();
158
+ return;
159
+ }
135
160
  // 根据响应类型输出内容
136
161
  switch (session.restype) {
137
162
  case 'plain':
@@ -154,12 +179,26 @@ export class Server {
154
179
  }
155
180
  };
156
181
  // 分发请求
157
- if (route && route.allowedMethods.includes(req.method ?? 'GET')) {
182
+ if (route && route.hasHandler(req.method ?? 'GET')) {
158
183
  await handleRoute(pathname);
159
184
  }
160
- else if (rootroute && rootroute.allowedMethods.includes(req.method ?? 'GET')) {
185
+ else if (route) {
186
+ res.writeHead(405, {
187
+ 'Allow': route.allowedMethods.filter(method => route.hasHandler(method)).join(', '),
188
+ 'Content-Type': 'text/plain',
189
+ });
190
+ res.end('Method Not Allowed');
191
+ }
192
+ else if (rootroute && rootroute.hasHandler(req.method ?? 'GET')) {
161
193
  await handleRoute('root');
162
194
  }
195
+ else if (rootroute) {
196
+ res.writeHead(405, {
197
+ 'Allow': rootroute.allowedMethods.filter(method => rootroute.hasHandler(method)).join(', '),
198
+ 'Content-Type': 'text/plain',
199
+ });
200
+ res.end('Method Not Allowed');
201
+ }
163
202
  else {
164
203
  res.writeHead(404, { 'Content-Type': 'text/plain' });
165
204
  res.end('Not Found');
@@ -167,6 +206,11 @@ export class Server {
167
206
  });
168
207
  // 处理 WebSocket 升级
169
208
  this.httpServer.on('upgrade', async (req, socket, head) => {
209
+ if (!this.enableWs) {
210
+ socket.write('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');
211
+ socket.destroy();
212
+ return;
213
+ }
170
214
  const url = new URL(req.url || '/', `http://${req.headers.host}`);
171
215
  const pathname = url.pathname;
172
216
  const queryParams = url.searchParams;
package/dist/service.d.ts CHANGED
File without changes
package/dist/service.js CHANGED
File without changes
package/dist/session.d.ts CHANGED
@@ -63,6 +63,7 @@ export interface StaticCacheOptions {
63
63
  }
64
64
  /** 响应体的数据类型分类 */
65
65
  type ResType = "plain" | "json" | "stream" | "buffer";
66
+ type RedirectStatus = 301 | 302 | 303 | 307 | 308;
66
67
  /** 响应类型与具体数据结构的映射表 */
67
68
  interface BodyMap {
68
69
  plain: string;
@@ -165,11 +166,19 @@ export declare class Session {
165
166
  get query(): Record<string, string> | undefined;
166
167
  /** 获取请求路径 */
167
168
  get pathname(): string;
169
+ /** 获取请求方法 */
170
+ get method(): string;
171
+ /** 获取请求中的 User-Agent */
172
+ get userAgent(): string;
173
+ /** 获取请求中的 Host */
174
+ get host(): string;
168
175
  /** 获取语言列表 */
169
176
  get languages(): string[];
170
177
  /** 获取请求协议 */
171
178
  get protocol(): string;
172
179
  set protocol(val: string);
180
+ /** 判断当前请求是否通过 HTTPS 访问 */
181
+ get isSecure(): boolean;
173
182
  /** 获取或设置响应状态码 */
174
183
  get status(): number;
175
184
  set status(val: number);
@@ -193,6 +202,32 @@ export declare class Session {
193
202
  * @param type 内容类型,默认为 'plain'
194
203
  */
195
204
  respond<T extends ResType>(body: BodyMap[T], type?: T): void;
205
+ /**
206
+ * 返回 JSON 响应
207
+ * @param data 要序列化的 JSON 数据
208
+ * @param status 可选的 HTTP 状态码
209
+ */
210
+ json(data: any, status?: number): void;
211
+ /**
212
+ * 返回 HTML 响应
213
+ * @param content HTML 内容
214
+ * @param status 可选的 HTTP 状态码
215
+ */
216
+ html(content: string, status?: number): void;
217
+ /**
218
+ * 返回纯文本响应
219
+ * @param content 文本内容
220
+ * @param status 可选的 HTTP 状态码
221
+ */
222
+ plain(content: string, status?: number): void;
223
+ /**
224
+ * 重定向客户端
225
+ * @param url 重定向目标地址
226
+ * @param status 重定向状态码,默认为 302
227
+ */
228
+ redirect(url: string, status?: RedirectStatus): void;
229
+ /** 返回 204 No Content 响应 */
230
+ noContent(): void;
196
231
  /** 获取响应类型 */
197
232
  get restype(): ResType;
198
233
  /** 获取响应体内容 */
@@ -206,6 +241,29 @@ export declare class Session {
206
241
  * @param options 配置项
207
242
  */
208
243
  setCookie(name: string, value: string, options?: CookieOptions): void;
244
+ /**
245
+ * 清除客户端 Cookie
246
+ * @param name Cookie 键名
247
+ * @param options Cookie 配置,通常应与设置时保持一致
248
+ */
249
+ removeCookie(name: string, options?: CookieOptions): void;
250
+ /**
251
+ * 获取会话数据
252
+ * @param key 数据键名
253
+ * @param defaultValue 数据不存在时返回的默认值
254
+ */
255
+ getData<T>(key: string, defaultValue?: T): T | undefined;
256
+ /**
257
+ * 设置响应头
258
+ * @param name 响应头名称
259
+ * @param value 响应头值
260
+ */
261
+ setHeader(name: string, value: string | number): void;
262
+ /**
263
+ * 获取响应头
264
+ * @param name 响应头名称,不区分大小写
265
+ */
266
+ getHeader(name: string): any;
209
267
  /**
210
268
  * 解析 Accept-Language 请求头
211
269
  * @param header 原始头字符串
package/dist/session.js CHANGED
@@ -126,11 +126,22 @@ export class Session {
126
126
  get query() { return this.request.query; }
127
127
  /** 获取请求路径 */
128
128
  get pathname() { return this.request.pathname; }
129
+ /** 获取请求方法 */
130
+ get method() { return this.request.raw?.method || ''; }
131
+ /** 获取请求中的 User-Agent */
132
+ get userAgent() { return this.request.headers['user-agent'] || ''; }
133
+ /** 获取请求中的 Host */
134
+ get host() { return this.request.headers.host || ''; }
129
135
  /** 获取语言列表 */
130
136
  get languages() { return this.request.languages; }
131
137
  /** 获取请求协议 */
132
138
  get protocol() { return this.request.protocol; }
133
139
  set protocol(val) { this.request.protocol = val; }
140
+ /** 判断当前请求是否通过 HTTPS 访问 */
141
+ get isSecure() {
142
+ const forwardedProtocol = this.request.headers['x-forwarded-proto']?.split(',')[0].trim();
143
+ return (forwardedProtocol || this.protocol).toLowerCase() === 'https';
144
+ }
134
145
  /** 获取或设置响应状态码 */
135
146
  get status() { return this.response.status; }
136
147
  set status(val) { this.response.status = val; }
@@ -160,6 +171,54 @@ export class Session {
160
171
  this.response.type = type;
161
172
  this.response.body = body;
162
173
  }
174
+ /**
175
+ * 返回 JSON 响应
176
+ * @param data 要序列化的 JSON 数据
177
+ * @param status 可选的 HTTP 状态码
178
+ */
179
+ json(data, status) {
180
+ if (status !== undefined)
181
+ this.status = status;
182
+ this.setMime('json');
183
+ this.respond(data, 'json');
184
+ }
185
+ /**
186
+ * 返回 HTML 响应
187
+ * @param content HTML 内容
188
+ * @param status 可选的 HTTP 状态码
189
+ */
190
+ html(content, status) {
191
+ if (status !== undefined)
192
+ this.status = status;
193
+ this.setMime('html');
194
+ this.respond(content, 'plain');
195
+ }
196
+ /**
197
+ * 返回纯文本响应
198
+ * @param content 文本内容
199
+ * @param status 可选的 HTTP 状态码
200
+ */
201
+ plain(content, status) {
202
+ if (status !== undefined)
203
+ this.status = status;
204
+ this.setMime('plain');
205
+ this.respond(content, 'plain');
206
+ }
207
+ /**
208
+ * 重定向客户端
209
+ * @param url 重定向目标地址
210
+ * @param status 重定向状态码,默认为 302
211
+ */
212
+ redirect(url, status = 302) {
213
+ this.status = status;
214
+ this.setHeader('Location', url);
215
+ this.respond('', 'plain');
216
+ }
217
+ /** 返回 204 No Content 响应 */
218
+ noContent() {
219
+ this.status = 204;
220
+ this.respond('', 'plain');
221
+ }
163
222
  /** 获取响应类型 */
164
223
  get restype() {
165
224
  return this.response.type;
@@ -185,6 +244,41 @@ export class Session {
185
244
  }
186
245
  this.response.cookies[name] = { value, options };
187
246
  }
247
+ /**
248
+ * 清除客户端 Cookie
249
+ * @param name Cookie 键名
250
+ * @param options Cookie 配置,通常应与设置时保持一致
251
+ */
252
+ removeCookie(name, options = {}) {
253
+ this.setCookie(name, '', { ...options, expires: new Date(0) });
254
+ }
255
+ /**
256
+ * 获取会话数据
257
+ * @param key 数据键名
258
+ * @param defaultValue 数据不存在时返回的默认值
259
+ */
260
+ getData(key, defaultValue) {
261
+ return this.data[key] === undefined ? defaultValue : this.data[key];
262
+ }
263
+ /**
264
+ * 设置响应头
265
+ * @param name 响应头名称
266
+ * @param value 响应头值
267
+ */
268
+ setHeader(name, value) {
269
+ this.response.headers[name] = value;
270
+ }
271
+ /**
272
+ * 获取响应头
273
+ * @param name 响应头名称,不区分大小写
274
+ */
275
+ getHeader(name) {
276
+ if (name in this.response.headers)
277
+ return this.response.headers[name];
278
+ const lowerName = name.toLowerCase();
279
+ const entry = Object.entries(this.response.headers).find(([key]) => key.toLowerCase() === lowerName);
280
+ return entry?.[1];
281
+ }
188
282
  /**
189
283
  * 解析 Accept-Language 请求头
190
284
  * @param header 原始头字符串
@@ -285,10 +379,31 @@ export class Session {
285
379
  * 获取请求体文本
286
380
  */
287
381
  async getReqBody(req) {
288
- return new Promise((resolve) => {
382
+ return new Promise((resolve, reject) => {
289
383
  let body = "";
290
- req.on('data', chunk => body += chunk.toString());
291
- req.on('end', () => resolve(body));
384
+ const cleanup = () => {
385
+ req.off('data', onData);
386
+ req.off('end', onEnd);
387
+ req.off('error', onError);
388
+ req.off('aborted', onAborted);
389
+ };
390
+ const onData = (chunk) => body += chunk.toString();
391
+ const onEnd = () => {
392
+ cleanup();
393
+ resolve(body);
394
+ };
395
+ const onError = (error) => {
396
+ cleanup();
397
+ reject(error);
398
+ };
399
+ const onAborted = () => {
400
+ cleanup();
401
+ reject(new Error('Request body was aborted.'));
402
+ };
403
+ req.on('data', onData);
404
+ req.once('end', onEnd);
405
+ req.once('error', onError);
406
+ req.once('aborted', onAborted);
292
407
  });
293
408
  }
294
409
  /**
package/dist/storage.d.ts CHANGED
@@ -30,9 +30,26 @@ export declare class SessionStorageProcessor {
30
30
  constructor(storage?: Storage<SessionStorageSnapshot>, options?: SessionStorageOptions);
31
31
  setStorage(storage: Storage<SessionStorageSnapshot>): void;
32
32
  getStorage(): Storage<SessionStorageSnapshot>;
33
+ /**
34
+ * 加载会话数据
35
+ * @param sessionid 会话ID
36
+ * @returns 会话数据
37
+ */
33
38
  load(sessionid: string): Promise<Record<string, any>>;
39
+ /**
40
+ * 保存会话数据
41
+ * @param sessionid 会话ID
42
+ * @param data 会话数据
43
+ */
34
44
  save(sessionid: string, data: Record<string, any>): Promise<void>;
45
+ /**
46
+ * 删除会话数据
47
+ * @param sessionid 会话ID
48
+ */
35
49
  delete(sessionid: string): Promise<void>;
50
+ /**
51
+ * 清空所有会话数据
52
+ */
36
53
  clear(): Promise<void>;
37
54
  private getKey;
38
55
  private isExpired;
package/dist/storage.js CHANGED
@@ -28,6 +28,11 @@ export class SessionStorageProcessor {
28
28
  getStorage() {
29
29
  return this.storage;
30
30
  }
31
+ /**
32
+ * 加载会话数据
33
+ * @param sessionid 会话ID
34
+ * @returns 会话数据
35
+ */
31
36
  async load(sessionid) {
32
37
  const snapshot = await this.storage.get(this.getKey(sessionid));
33
38
  if (!snapshot)
@@ -38,6 +43,11 @@ export class SessionStorageProcessor {
38
43
  }
39
44
  return { ...(snapshot.data || {}) };
40
45
  }
46
+ /**
47
+ * 保存会话数据
48
+ * @param sessionid 会话ID
49
+ * @param data 会话数据
50
+ */
41
51
  async save(sessionid, data) {
42
52
  const key = this.getKey(sessionid);
43
53
  const now = Date.now();
@@ -52,9 +62,16 @@ export class SessionStorageProcessor {
52
62
  };
53
63
  await this.storage.set(key, snapshot);
54
64
  }
65
+ /**
66
+ * 删除会话数据
67
+ * @param sessionid 会话ID
68
+ */
55
69
  async delete(sessionid) {
56
70
  await this.storage.delete(this.getKey(sessionid));
57
71
  }
72
+ /**
73
+ * 清空所有会话数据
74
+ */
58
75
  async clear() {
59
76
  if (this.storage.clear) {
60
77
  await this.storage.clear();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yumerijs/core",
3
- "version": "3.0.6",
3
+ "version": "3.1.5",
4
4
  "description": "Core module for yumeri",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -30,7 +30,7 @@
30
30
  "@types/formidable": "^3",
31
31
  "@types/js-yaml": "^4.0.9",
32
32
  "@types/mime-types": "^3",
33
- "@types/node": "^22.13.10",
33
+ "@types/node": "^26.6.6",
34
34
  "@types/semver": "^7",
35
35
  "@types/ws": "^8",
36
36
  "typescript": "^6.0.3"