mm_machine 3.5.4 → 3.5.6

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/mod.js CHANGED
@@ -1,41 +1,16 @@
1
- const { Base } = require('mm_expand');
2
- require('./auto_require.js');
3
-
4
- /**
5
- * 增强JSON加载函数,专门用于配置文件(.json)热重载
6
- * 当配置文件内容发生变化时,自动重新加载并触发回调
7
- * @param {string} file 配置文件路径(.json)
8
- * @param {Function} func 热更新回调函数,文件变化时触发
9
- * @returns {object} 解析的JSON对象
10
- * @throws {TypeError} 文件路径不是字符串或回调不是函数时抛出
11
- */
12
- $.loadJson = function (file, func) {
13
- // 参数校验
14
- if (typeof file !== 'string') {
15
- throw new TypeError('第一个参数(file)必须是字符串');
16
- }
17
-
18
- if (func && typeof func !== 'function') {
19
- throw new TypeError('第二个参数(func)必须是函数');
20
- }
21
-
22
- // 确保文件是.json文件
23
- if (!file.endsWith('.json')) {
24
- throw new TypeError('$.loadJson 只能用于.json配置文件');
25
- }
26
- return $.mod.load(file, func);
27
- };
1
+ const { Mod: CoreMod } = require('mm_mod');
2
+ const { saveJson, loadJson } = require('mm_helper');
28
3
 
29
4
  /**
30
5
  * 通用模块类
6
+ * @description 在 mm_mod.Mod 的生命周期、配置与日志能力之上,提供插件式调度(do 流水线)、
7
+ * 脚本方法/数据挂载、加载与卸载、缓存数据持久化等能力
31
8
  */
32
- class Mod extends Base {
9
+ class Mod extends CoreMod {
33
10
  /**
34
11
  * 配置项
35
12
  */
36
13
  static config = {
37
- // 模块名称(唯一标识)
38
- name: '',
39
14
  // 模块标题(中文名称)
40
15
  title: '',
41
16
  // 模块描述
@@ -48,15 +23,12 @@ class Mod extends Base {
48
23
  cache_file: ''
49
24
  };
50
25
 
51
- _is_loaded = false;
52
- _is_inited = false;
53
-
54
26
  /**
55
27
  * 构造函数
56
28
  * @param {object} config 配置对象
57
29
  * @param {object} parent 父模块
58
30
  */
59
- constructor(config, parent) {
31
+ constructor(config = {}, parent) {
60
32
  super(config, parent);
61
33
  if (parent) {
62
34
  this.getParent = function () {
@@ -67,46 +39,73 @@ class Mod extends Base {
67
39
  this._methods = {};
68
40
  // 脚本数据
69
41
  this._datas = {};
42
+ // 监听事件
43
+ this._listen();
70
44
  }
45
+ }
71
46
 
72
- /**
73
- * 是否已加载
74
- * @param {boolean} bl 是否已加载
75
- * @returns {boolean} 是否已加载
76
- */
77
- isLoaded(bl) {
78
- if (bl === undefined) {
79
- return this._is_loaded;
80
- }
81
- this._is_loaded = bl;
82
- if (!bl) {
83
- this._is_inited = false;
84
- }
85
- return bl;
86
- }
47
+ /**
48
+ * 初始化(兼容 mm_expand 行为,生命周期由 do 流水线驱动)
49
+ * @returns {Promise<Mod>} 当前实例
50
+ */
51
+ Mod.prototype._init = async function () {
52
+ return this;
53
+ };
87
54
 
88
- /**
89
- * 是否已初始化
90
- * @param {boolean} bl 是否已初始化
91
- * @returns {boolean} 是否已初始化
92
- */
93
- isInited(bl) {
94
- if (bl === undefined) {
95
- return this._is_inited;
96
- }
97
- this._is_inited = bl;
98
- return bl;
99
- }
100
- }
55
+ /**
56
+ * 初始化
57
+ * @returns {Promise<Mod>} 当前实例
58
+ */
59
+ Mod.prototype.init = async function () {
60
+ return await this._init();
61
+ };
62
+
63
+ /**
64
+ * 启动(兼容 mm_expand 行为,生命周期由 do 流水线驱动)
65
+ * @returns {Promise<Mod>} 当前实例
66
+ */
67
+ Mod.prototype._start = async function () {
68
+ return this;
69
+ };
101
70
 
102
71
  /**
103
- * 日志输出
104
- * @param {string} level 日志级别
105
- * @param {string} message 日志消息
106
- * @param {...any} params 日志参数
72
+ * 启动
73
+ * @returns {Promise<Mod>} 当前实例
107
74
  */
108
- Mod.prototype.log = function (level, message, ...params) {
109
- this.getLogger()[level](`[${this.constructor.name}.${this.config.name}] ${message}`, ...params);
75
+ Mod.prototype.start = async function () {
76
+ return await this._start();
77
+ };
78
+
79
+ /**
80
+ * 停止(兼容 mm_expand 行为,生命周期由 do 流水线驱动)
81
+ * @returns {Promise<Mod>} 当前实例
82
+ */
83
+ Mod.prototype._stop = async function () {
84
+ return this;
85
+ };
86
+
87
+ /**
88
+ * 停止
89
+ * @returns {Promise<Mod>} 当前实例
90
+ */
91
+ Mod.prototype.stop = async function () {
92
+ return await this._stop();
93
+ };
94
+
95
+ /**
96
+ * 销毁(兼容 mm_expand 行为,生命周期由 do 流水线驱动)
97
+ * @returns {Promise<Mod>} 当前实例
98
+ */
99
+ Mod.prototype._destroy = async function () {
100
+ return this;
101
+ };
102
+
103
+ /**
104
+ * 销毁
105
+ * @returns {Promise<Mod>} 当前实例
106
+ */
107
+ Mod.prototype.destroy = async function () {
108
+ return await this._destroy();
110
109
  };
111
110
 
112
111
  /**
@@ -162,210 +161,112 @@ Mod.prototype._listen = function () {
162
161
 
163
162
  /**
164
163
  * 监听加载事件
165
- * @param {object} ctx 上下文对象
166
164
  */
167
- Mod.prototype._onLoad = async function (ctx) {
165
+ Mod.prototype._onLoad = function () {
168
166
  // 1. 加载
169
167
  this.on('load:before', async (ctx) => {
170
- this.setState('loading');
171
168
  await this._loadCore(...ctx.params);
172
169
  });
173
- this.on('load:after', (ctx) => {
174
- this.setState('loaded');
175
- this.isLoaded(true);
176
- });
177
170
  };
178
171
 
179
172
  /**
180
173
  * 监听初始化事件
181
174
  */
182
- Base.prototype._onInit = function () {
175
+ Mod.prototype._onInit = function () {
183
176
  // 初始化
184
177
  this.on('init:before', async (ctx) => {
185
- this.setState('initing');
186
178
  await this._initCore(...ctx.params);
187
179
  });
188
- this.on('init:success', (ctx) => {
189
- this.isInited(true);
190
- });
191
- this.on('init:after', (ctx) => {
192
- this.setState('inited');
193
- });
194
180
  };
195
181
 
196
182
  /**
197
183
  * 监听启动事件
198
- * @param {object} ctx 上下文对象
199
184
  */
200
- Mod.prototype._onStart = async function (ctx) {
201
- let status_last = 'inited';
185
+ Mod.prototype._onStart = function () {
202
186
  // 3. 启动
203
187
  this.on('start:before', async (ctx) => {
204
- status_last = this.getState();
205
- this.setState('starting');
206
188
  await this._startCore(...ctx.params);
207
189
  });
208
- this.on('start:success', (ctx) => {
209
- this.setState('running');
210
- });
211
- this.on('start:error', (ctx) => {
212
- this.setState(status_last);
213
- });
214
190
  };
215
191
 
216
192
  /**
217
193
  * 监听停止事件
218
- * @param {object} ctx 上下文对象
219
194
  */
220
- Mod.prototype._onStop = async function (ctx) {
221
- let status_last = 'running';
195
+ Mod.prototype._onStop = function () {
222
196
  // 4. 停止
223
- this.on('stop:before', async (ctx) => {
224
- status_last = this.getState();
225
- this.setState('stopping');
226
- });
227
197
  this.on('stop:after', async (ctx) => {
228
198
  await this._stopCore(...ctx.params);
229
199
  });
230
- this.on('stop:success', async (ctx) => {
231
- this.setState('stopped');
232
- });
233
- this.on('stop:error', (ctx) => {
234
- this.setState(status_last);
235
- });
236
200
  };
237
201
 
238
202
  /**
239
203
  * 监听销毁事件
240
204
  */
241
205
  Mod.prototype._onDestroy = function () {
242
- let status_last = 'stopped';
243
206
  // 销毁
244
- this.on('destroy:before', async (ctx) => {
245
- status_last = this.getState();
246
- this.setState('destroying');
247
- });
248
- this.on('destroy:check', (ctx) => {
249
- if (status_last !== 'unloaded') {
250
- this.setState(status_last);
251
- ctx.error = new Error('销毁前必须先卸载');
252
- }
253
- });
254
207
  this.on('destroy:after', async (ctx) => {
255
208
  await this._destroyCore(...ctx.params);
256
209
  });
257
- this.on('destroy:success', (ctx) => {
258
- this.setState('destroyed');
259
- });
260
- this.on('destroy:error', (ctx) => {
261
- this.setState(status_last);
262
- });
263
210
  };
264
211
 
265
212
  /**
266
213
  * 监听卸载事件
267
- * @param {object} ctx 上下文对象
268
214
  */
269
- Mod.prototype._onUnload = async function (ctx) {
270
- let status_last = 'stopped';
215
+ Mod.prototype._onUnload = function () {
271
216
  // 5. 卸载
272
- this.on('unload:before', (ctx) => {
273
- status_last = this.getState();
274
- this.setState('unloading');
275
- });
276
- this.on('unload:check', (ctx) => {
277
- if (status_last !== 'stopped') {
278
- status_last = this.getState();
279
- ctx.error = new Error('卸载前必须先停止');
280
- }
281
- });
282
217
  this.on('unload:after', async (ctx) => {
283
- this.setState('unloaded');
284
218
  await this._unloadCore(...ctx.params);
285
- this.isLoaded(false);
286
219
  });
287
220
  };
288
221
 
289
222
  /**
290
223
  * 加载 - 内部方法
291
- * @param {...any} args 加载参数
292
- * @returns {object} 模块对象
224
+ * @returns {Promise<Mod>} 模块对象
293
225
  * @private
294
226
  */
295
- Mod.prototype._load = async function (...args) {
227
+ Mod.prototype._load = async function () {
296
228
  return this;
297
229
  };
298
230
 
299
231
  /**
300
232
  * 加载
301
- * @param {...any} args 加载参数
302
- * @returns {object} 模块对象
233
+ * @returns {Promise<Mod>} 模块对象
303
234
  */
304
- Mod.prototype.load = async function (...args) {
305
- return await this._load(...args);
235
+ Mod.prototype.load = async function () {
236
+ return await this._load();
306
237
  };
307
238
 
308
239
  /**
309
240
  * 加载核心
241
+ * @returns {Promise<void>} 无返回值
310
242
  * @private
311
- * @param {...any} args 加载参数
312
- */
313
- Mod.prototype._loadCore = async function (...args) {
314
-
315
- };
316
-
317
- /**
318
- * 启动 - 内部方法
319
- * @private
320
- * @param {...any} args 初始化参数
321
- * @returns {object} 模块对象
322
- */
323
- Mod.prototype._start = async function (...args) {
324
- return this;
325
- };
326
-
327
- /**
328
- * 启动
329
- * @param {...any} args 初始化参数
330
- * @returns {object} 模块对象
331
243
  */
332
- Mod.prototype.start = async function (...args) {
333
- return await this._start(...args);
334
- };
244
+ Mod.prototype._loadCore = async function () { };
335
245
 
336
246
  /**
337
247
  * 启动核心
248
+ * @returns {Promise<void>} 无返回值
338
249
  * @private
339
- * @param {...any} args 初始化参数
340
250
  */
341
- Mod.prototype._startCore = async function (...args) { };
251
+ Mod.prototype._startCore = async function () { };
342
252
 
343
253
  /**
344
- * 停止 - 内部方法
254
+ * 停止核心
255
+ * @returns {Promise<void>} 无返回值
345
256
  * @private
346
- * @returns {object} 模块对象
347
257
  */
348
- Mod.prototype._stop = async function () {
349
- return this;
350
- };
351
-
352
- /**
353
- * 停止
354
- * @returns {object} 模块对象
355
- */
356
- Mod.prototype.stop = async function () {
357
- return await this._stop();
358
- };
258
+ Mod.prototype._stopCore = async function () { };
359
259
 
360
260
  /**
361
- * 停止核心
261
+ * 初始化核心
262
+ * @returns {Promise<void>} 无返回值
362
263
  * @private
363
264
  */
364
- Mod.prototype._stopCore = async function () { };
265
+ Mod.prototype._initCore = async function () { };
365
266
 
366
267
  /**
367
268
  * 销毁核心
368
- * @returns {object} 返回当前对象
269
+ * @returns {Promise<void>} 无返回值
369
270
  */
370
271
  Mod.prototype._destroyCore = async function () {
371
272
  if (this.config.need_cache) {
@@ -377,8 +278,8 @@ Mod.prototype._destroyCore = async function () {
377
278
 
378
279
  /**
379
280
  * 卸载 - 内部方法
281
+ * @returns {Promise<Mod>} 模块对象
380
282
  * @private
381
- * @returns {object} 模块对象
382
283
  */
383
284
  Mod.prototype._unload = async function () {
384
285
  return this;
@@ -386,7 +287,7 @@ Mod.prototype._unload = async function () {
386
287
 
387
288
  /**
388
289
  * 卸载
389
- * @returns {object} 模块对象
290
+ * @returns {Promise<Mod>} 模块对象
390
291
  */
391
292
  Mod.prototype.unload = async function () {
392
293
  return await this._unload();
@@ -394,6 +295,7 @@ Mod.prototype.unload = async function () {
394
295
 
395
296
  /**
396
297
  * 卸载核心
298
+ * @returns {Promise<void>} 无返回值
397
299
  */
398
300
  Mod.prototype._unloadCore = async function () {
399
301
  if (this._methods) {
@@ -412,11 +314,11 @@ Mod.prototype._unloadCore = async function () {
412
314
 
413
315
  /**
414
316
  * 重载
317
+ * @returns {Promise<void>} 无返回值
415
318
  */
416
319
  Mod.prototype.reload = async function () {
417
320
  try {
418
- this._unloadCore();
419
- this.isLoaded(false);
321
+ await this._unloadCore();
420
322
  } catch (err) {
421
323
  this.log('error', '重载失败', err);
422
324
  }
@@ -424,6 +326,7 @@ Mod.prototype.reload = async function () {
424
326
 
425
327
  /**
426
328
  * 重启
329
+ * @returns {Promise<void>} 无返回值
427
330
  */
428
331
  Mod.prototype.restart = async function () {
429
332
  try {
@@ -434,16 +337,9 @@ Mod.prototype.restart = async function () {
434
337
  }
435
338
  };
436
339
 
437
- /**
438
- * 是否运行中
439
- * @returns {boolean} 是否运行中
440
- */
441
- Mod.prototype.isRunning = function () {
442
- return this.getState() === 'running';
443
- };
444
-
445
340
  /**
446
341
  * 结束
342
+ * @returns {Promise<void>} 无返回值
447
343
  */
448
344
  Mod.prototype.end = async function () {
449
345
  try {
@@ -455,12 +351,263 @@ Mod.prototype.end = async function () {
455
351
  }
456
352
  };
457
353
 
354
+ /**
355
+ * 事件驱动
356
+ * @param {string} method 方法名称
357
+ * @param {...any} params 参数列表
358
+ * @returns {Promise<any>} 执行结果
359
+ */
360
+ Mod.prototype.do = async function (method, ...params) {
361
+ let ctx = await this._do(method, ...params);
362
+ return ctx.result;
363
+ };
364
+
365
+ /**
366
+ * 事件驱动 - 内部方法
367
+ * @param {string} method 方法名称
368
+ * @param {...any} params 参数列表
369
+ * @returns {Promise<object>} 执行上下文对象
370
+ */
371
+ Mod.prototype._do = async function (method, ...params) {
372
+ // 入参校验
373
+ if (!method || typeof method !== 'string') {
374
+ throw new TypeError('方法名必须是非空字符串');
375
+ }
376
+
377
+ if (!this[method]) {
378
+ throw new Error(`方法${method}不存在`);
379
+ }
380
+
381
+ let ctx = {
382
+ method,
383
+ params,
384
+ result: undefined,
385
+ error: undefined,
386
+ cancelled: false
387
+ };
388
+
389
+ try {
390
+ await this._doBeforeProcess(method, ctx);
391
+ if (ctx.cancelled) {
392
+ return ctx;
393
+ }
394
+
395
+ await this._doExecuteMethod(method, ctx);
396
+ } catch (error) {
397
+ ctx.error = error;
398
+ }
399
+ if (ctx.error) {
400
+ // 执行错误处理
401
+ await this._doErrorProcess(method, ctx);
402
+ } else {
403
+ // 如果执行成功,进行成功处理
404
+ await this._doSuccessProcess(method, ctx);
405
+ }
406
+ // 无论成功失败,都要执行后处理
407
+ await this._doAfterProcess(method, ctx);
408
+ return ctx;
409
+ };
410
+
411
+ /**
412
+ * 前处理阶段
413
+ * @param {string} method 方法名称
414
+ * @param {object} ctx 上下文对象
415
+ * @returns {Promise<void>} 无返回值
416
+ * @private
417
+ */
418
+ Mod.prototype._doBeforeProcess = async function (method, ctx) {
419
+ await this.emitWait(method + ':before', ctx);
420
+ };
421
+
422
+ /**
423
+ * 执行方法
424
+ * @param {string} method 方法名称
425
+ * @param {object} ctx 上下文对象
426
+ * @returns {Promise<void>} 无返回值
427
+ * @private
428
+ */
429
+ Mod.prototype._doExecuteMethod = async function (method, ctx) {
430
+ await this._doCheckPhase(method, ctx);
431
+ if (ctx.error) return;
432
+
433
+ await this._doMainMethod(method, ctx);
434
+ if (ctx.error) return;
435
+
436
+ await this._doRenderPhase(method, ctx);
437
+ };
438
+
439
+ /**
440
+ * 检查阶段
441
+ * @param {string} method 方法名称
442
+ * @param {object} ctx 上下文对象
443
+ * @returns {Promise<void>} 无返回值
444
+ */
445
+ Mod.prototype._doCheckPhase = async function (method, ctx) {
446
+ let ret = await this.emitRace(method + ':check', ctx);
447
+
448
+ if (ret) {
449
+ if (ret.status === 'rejected') {
450
+ ctx.error = ret.error;
451
+ } else if (ret.status === 'fulfilled' && ret.result) {
452
+ ctx.result = ret.result;
453
+ }
454
+ }
455
+ };
456
+
457
+ /**
458
+ * 主方法执行
459
+ * @param {string} method 方法名称
460
+ * @param {object} ctx 上下文对象
461
+ * @returns {Promise<void>} 无返回值
462
+ * @private
463
+ */
464
+ Mod.prototype._doMainMethod = async function (method, ctx) {
465
+ if (!ctx.result) {
466
+ // 触发执行中事件
467
+ let result = await this.emitWait(`${method}:main`, ctx);
468
+ if (result) {
469
+ ctx.result = result;
470
+ }
471
+
472
+ if (!ctx.result) {
473
+ // 调用子类实现的逻辑
474
+ ctx.result = await this[method](...ctx.params);
475
+ }
476
+ }
477
+ };
478
+
479
+ /**
480
+ * 渲染阶段
481
+ * @param {string} method 方法名称
482
+ * @param {object} ctx 上下文对象
483
+ * @returns {Promise<void>} 无返回值
484
+ * @private
485
+ */
486
+ Mod.prototype._doRenderPhase = async function (method, ctx) {
487
+ if (ctx.result && !ctx.error) {
488
+ let result = await this.emitWate(method + ':render', ctx.result, ctx);
489
+ if (result) {
490
+ ctx.result = result;
491
+ }
492
+ }
493
+ };
494
+
495
+ /**
496
+ * 成功处理阶段
497
+ * @param {string} method 方法名称
498
+ * @param {object} ctx 上下文对象
499
+ * @returns {Promise<void>} 无返回值
500
+ * @private
501
+ */
502
+ Mod.prototype._doSuccessProcess = async function (method, ctx) {
503
+ await this.emitWait(method + ':success', ctx);
504
+ };
505
+
506
+ /**
507
+ * 后处理阶段
508
+ * @param {string} method 方法名称
509
+ * @param {object} ctx 上下文对象
510
+ * @returns {Promise<void>} 无返回值
511
+ * @private
512
+ */
513
+ Mod.prototype._doAfterProcess = async function (method, ctx) {
514
+ // 顺序执行并等待,确保后处理在本次调度结束前完成
515
+ await this.emitWait(method + ':after', ctx);
516
+ };
517
+
518
+ /**
519
+ * 错误处理
520
+ * @param {string} method 方法名称
521
+ * @param {object} ctx 上下文对象
522
+ * @returns {Promise<void>} 无返回值
523
+ */
524
+ Mod.prototype._doErrorProcess = async function (method, ctx) {
525
+ if (ctx.error) {
526
+ // 顺序执行并等待,确保错误处理在本次调度结束前完成
527
+ await this.emitWait(method + ':error', ctx);
528
+ this.log('error', `执行方法${method}出错:`, ctx.error);
529
+ }
530
+ };
531
+
532
+ /**
533
+ * 快速执行方法
534
+ * @param {string} method 方法名称
535
+ * @param {...any} params 参数列表
536
+ * @returns {Promise<any>} 执行结果
537
+ */
538
+ Mod.prototype.doEasy = async function (method, ...params) {
539
+ // 快速检查方法是否存在
540
+ if (!this[method]) {
541
+ throw new Error(`方法${method}不存在`);
542
+ }
543
+
544
+ try {
545
+ // 直接执行主方法,跳过所有事件处理
546
+ return await this[method](...params);
547
+ } catch (error) {
548
+ // 简单错误处理
549
+ this.log('error', `快速执行方法${method}出错:`, error);
550
+ }
551
+ };
552
+
553
+ /**
554
+ * 智能执行方法(自动选择 do 或 doEasy)
555
+ * @param {string} method 方法名称
556
+ * @param {...any} params 参数列表
557
+ * @returns {Promise<any>} 执行结果
558
+ */
559
+ Mod.prototype.doSmart = async function (method, ...params) {
560
+ // 提取选项参数
561
+ let options = {};
562
+ if (params.length > 0 && typeof params[params.length - 1] === 'object') {
563
+ options = params.pop();
564
+ }
565
+
566
+ // 检查是否有监听器
567
+ let has_list = this._hasEventListeners(method);
568
+
569
+ // 根据选项和监听器情况选择执行方式
570
+ if (options.fast || !has_list) {
571
+ // 快速执行:无监听器或明确要求快速
572
+ return await this.doEasy(method, ...params);
573
+ } else {
574
+ // 完整事件驱动执行
575
+ return await this.do(method, ...params);
576
+ }
577
+ };
578
+
579
+ /**
580
+ * 检查方法是否有事件监听器
581
+ * @param {string} method 方法名称
582
+ * @returns {boolean} 是否有监听器
583
+ * @private
584
+ */
585
+ Mod.prototype._hasEventListeners = function (method) {
586
+ return (
587
+ this.listenerCount(method + ':before') > 0 ||
588
+ this.listenerCount(method + ':check') > 0 ||
589
+ this.listenerCount(method + ':render') > 0 ||
590
+ this.listenerCount(method + ':success') > 0 ||
591
+ this.listenerCount(method + ':error') > 0 ||
592
+ this.listenerCount(method + ':after') > 0
593
+ );
594
+ };
595
+
596
+ /**
597
+ * 执行入口
598
+ * @param {...any} params 参数列表
599
+ * @returns {Promise<any>} 执行结果
600
+ */
601
+ Mod.prototype.run = async function (...params) {
602
+ return await this.do('main', ...params);
603
+ };
604
+
458
605
  /**
459
606
  * 获取事件管理器
460
607
  * @returns {object} 事件管理器
461
608
  */
462
609
  Mod.prototype.getEventer = function () {
463
- return this._eventer || $.eventer;
610
+ return this._eventer || this;
464
611
  };
465
612
 
466
613
  /**
@@ -471,6 +618,127 @@ Mod.prototype.setEventer = function (eventer) {
471
618
  this._eventer = eventer;
472
619
  };
473
620
 
621
+ /**
622
+ * 触发事件 - 顺序执行并等待完成
623
+ * @param {string} event 事件名
624
+ * @param {...any} args 事件参数
625
+ * @returns {Promise<void>} 无返回值
626
+ */
627
+ Mod.prototype.emitWait = async function (event, ...args) {
628
+ let listeners = this.listeners(event);
629
+ for (let listener of listeners) {
630
+ try {
631
+ await listener(...args);
632
+ } catch (error) {
633
+ this._handleError(error, event);
634
+ }
635
+ }
636
+ };
637
+
638
+ /**
639
+ * 触发事件 - 并发执行不等待
640
+ * @param {string} event 事件名
641
+ * @param {...any} args 事件参数
642
+ * @returns {boolean} 是否成功触发事件
643
+ */
644
+ Mod.prototype.emitAsync = function (event, ...args) {
645
+ let listeners = this.listeners(event);
646
+ if (listeners.length === 0) return false;
647
+
648
+ listeners.forEach((listener) => {
649
+ Promise.resolve()
650
+ .then(() => listener(...args))
651
+ .catch((error) => {
652
+ this._handleError(error, event);
653
+ });
654
+ });
655
+
656
+ return true;
657
+ };
658
+
659
+ /**
660
+ * 触发事件 - 并发执行并等待完成
661
+ * @param {string} event 事件名
662
+ * @param {...any} args 事件参数
663
+ * @returns {Promise<Array>} 所有监听器的执行结果
664
+ */
665
+ Mod.prototype.emitAll = async function (event, ...args) {
666
+ let listeners = this.listeners(event);
667
+ let promises = listeners.map((listener) => Promise.resolve().then(() => listener(...args)));
668
+ return await Promise.all(promises);
669
+ };
670
+
671
+ /**
672
+ * 触发事件 - 竞争执行
673
+ * @param {string} event 事件名
674
+ * @param {...any} args 事件参数
675
+ * @returns {Promise<object|null>} 第一个完成的结果
676
+ */
677
+ Mod.prototype.emitRace = async function (event, ...args) {
678
+ let listeners = this.listeners(event);
679
+ if (listeners.length === 0) return null;
680
+
681
+ let promises = listeners.map((listener, index) =>
682
+ Promise.resolve()
683
+ .then(() => listener(...args))
684
+ .then((result) => ({ index, result, status: 'fulfilled' }))
685
+ .catch((error) => ({ index, error, status: 'rejected' }))
686
+ );
687
+
688
+ return await Promise.race(promises);
689
+ };
690
+
691
+ /**
692
+ * 触发事件 - 瀑布流执行
693
+ * @param {string} event 事件名
694
+ * @param {*} value 初始值
695
+ * @param {...any} args 事件参数
696
+ * @returns {Promise<any>} 最后一个监听器的结果
697
+ */
698
+ Mod.prototype.emitWate = async function (event, value, ...args) {
699
+ let listeners = this.listeners(event);
700
+ let result = value;
701
+
702
+ for (let listener of listeners) {
703
+ try {
704
+ result = await listener(result, ...args);
705
+ } catch (error) {
706
+ this._handleError(error, event);
707
+ throw error;
708
+ }
709
+ }
710
+
711
+ return result;
712
+ };
713
+
714
+ /**
715
+ * 触发事件 - 返回第一个非空结果
716
+ * @param {string} event 事件名
717
+ * @param {...any} args 事件参数
718
+ * @returns {Promise<any>} 第一个非空结果
719
+ */
720
+ Mod.prototype.emitFirst = async function (event, ...args) {
721
+ let listeners = this.listeners(event);
722
+ for (let listener of listeners) {
723
+ let result = await listener(...args);
724
+ if (result !== undefined && result !== null) {
725
+ return result;
726
+ }
727
+ }
728
+ return undefined;
729
+ };
730
+
731
+ /**
732
+ * 事件错误处理
733
+ * @param {Error} error 错误对象
734
+ * @param {string} event 事件名
735
+ * @returns {void}
736
+ * @private
737
+ */
738
+ Mod.prototype._handleError = function (error, event) {
739
+ this.log('error', `事件 ${event} 执行失败:`, error);
740
+ };
741
+
474
742
  /**
475
743
  * 触发事件
476
744
  * @param {string} event 事件名
@@ -481,7 +749,7 @@ Mod.prototype.emitEvent = function (event, ...args) {
481
749
  };
482
750
 
483
751
  /**
484
- * 触发事件 - 随机触发
752
+ * 触发事件 - 竞争执行
485
753
  * @param {string} event 事件名
486
754
  * @param {...any} args 事件参数
487
755
  * @returns {Promise<any>} 事件触发结果
@@ -640,8 +908,7 @@ Mod.prototype.setData = function (key, value) {
640
908
  if (key === '_methods') {
641
909
  throw new Error(`第一个参数(key)不能为_methods键`);
642
910
  }
643
- if (value === undefined || value === null)
644
- throw new Error(`第二个参数(value)不能为undefined或null`);
911
+ if (value === undefined || value === null) throw new Error(`第二个参数(value)不能为undefined或null`);
645
912
  if (typeof value == 'function') {
646
913
  throw new Error(`第二个参数(value)不能为函数`);
647
914
  }
@@ -659,26 +926,26 @@ Mod.prototype.getCacheFile = function () {
659
926
 
660
927
  /**
661
928
  * 保存数据
929
+ * @returns {void}
662
930
  */
663
931
  Mod.prototype.saveDatas = function () {
664
932
  let datas = this.getDatas();
665
- let file = this.getCacheFile();
666
- file.saveJson(datas);
933
+ saveJson(this.getCacheFile(), datas);
667
934
  };
668
935
 
669
936
  /**
670
937
  * 加载数据
938
+ * @returns {void}
671
939
  */
672
940
  Mod.prototype.loadDatas = function () {
673
- let file = this.getCacheFile();
674
- let datas = file.loadJson();
941
+ let datas = loadJson(this.getCacheFile());
675
942
  this.setDatas(datas);
676
943
  };
677
944
 
678
945
  /**
679
946
  * 调用函数(核心执行方法)
680
947
  * @param {string} method 函数名
681
- * @param {*} params 参数集合
948
+ * @param {...any} params 参数集合
682
949
  * @returns {Promise<any>} 执行结果
683
950
  */
684
951
  Mod.prototype.call = async function (method, ...params) {
@@ -690,9 +957,9 @@ Mod.prototype.call = async function (method, ...params) {
690
957
  let result;
691
958
 
692
959
  try {
693
- let before_result = await this._callBefore(method, params);
694
- if (before_result) return before_result;
695
- result = await this._callMain(method_func, params, before_result);
960
+ let before = await this._callBefore(method, params);
961
+ if (before) return before;
962
+ result = await this._callMain(method_func, params, before);
696
963
  result = await this._callAfter(method, params, result);
697
964
  } catch (err) {
698
965
  this.log('error', `执行 ${method} 失败: ${err.message}`, this._wrapError(err, { method: method }));
@@ -776,6 +1043,26 @@ Mod.prototype.getDir = function () {
776
1043
  return parent.getDir();
777
1044
  };
778
1045
 
1046
+ /**
1047
+ * 将模块类的方法复制到目标类原型
1048
+ * @description 供继承其它基类的类复用模块能力;目标类已有的自有成员不会被覆盖
1049
+ * @param {Function} cs 目标类
1050
+ * @returns {Function} 目标类
1051
+ */
1052
+ function addModMethods(cs) {
1053
+ if (typeof cs !== 'function') {
1054
+ throw new TypeError('参数(cs)必须是类');
1055
+ }
1056
+ let names = Object.getOwnPropertyNames(Mod.prototype);
1057
+ for (let name of names) {
1058
+ if (name === 'constructor') continue;
1059
+ if (Object.prototype.hasOwnProperty.call(cs.prototype, name)) continue;
1060
+ Object.defineProperty(cs.prototype, name, Object.getOwnPropertyDescriptor(Mod.prototype, name));
1061
+ }
1062
+ return cs;
1063
+ }
1064
+
779
1065
  module.exports = {
780
- Mod
1066
+ Mod,
1067
+ addModMethods
781
1068
  };