mm_machine 3.1.0 → 3.1.2

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.
Files changed (4) hide show
  1. package/index.js +8 -10
  2. package/manager.js +220 -279
  3. package/package.json +1 -1
  4. package/registry.js +147 -158
package/index.js CHANGED
@@ -15,12 +15,10 @@ class Index {
15
15
  * @param {object} parent 父对象
16
16
  */
17
17
  constructor(config, parent) {
18
- this.config = Object.assign(
19
- {
20
- name: 'default'
21
- },
22
- config
23
- );
18
+ this.config = {
19
+ name: 'default',
20
+ ...config
21
+ };
24
22
 
25
23
  if (parent) {
26
24
  this.getParent = function () {
@@ -53,8 +51,8 @@ Index.prototype.load = function () {
53
51
  * @param {string} name 模块名
54
52
  * @returns {object|null} 模块实例
55
53
  */
56
- Index.prototype.getModule = function (name) {
57
- return $.registry.getModule(name);
54
+ Index.prototype.getMod = function (name) {
55
+ return $.registry.getMod(name);
58
56
  };
59
57
 
60
58
  /**
@@ -62,8 +60,8 @@ Index.prototype.getModule = function (name) {
62
60
  * @param {string} class_name 模块类名
63
61
  * @returns {Array} 模块实例数组
64
62
  */
65
- Index.prototype.getModules = function (class_name) {
66
- return $.registry.getModules(class_name);
63
+ Index.prototype.getMods = function (class_name) {
64
+ return $.registry.getMods(class_name);
67
65
  };
68
66
 
69
67
  module.exports = {
package/manager.js CHANGED
@@ -1,6 +1,7 @@
1
1
  const { Mod } = require('./mod');
2
2
  const { Drive } = require('./drive.js');
3
3
  const { Scanner } = require('./scanner.js');
4
+ const { Registry } = require('./registry.js');
4
5
 
5
6
  /**
6
7
  * 管理器类
@@ -86,7 +87,9 @@ class Manager extends Mod {
86
87
  * 作用域
87
88
  * @type {string}
88
89
  */
89
- scope: $.val && $.val.scope ? $.val.scope + '' : 'server'
90
+ scope: $.val && $.val.scope ? $.val.scope + '' : 'server',
91
+ // 触发字段,添加到注册表时注入此字段,可以避免先加载模块,满足触发条件后再加载
92
+ trigger_key: []
90
93
  };
91
94
 
92
95
  /**
@@ -106,18 +109,14 @@ class Manager extends Mod {
106
109
  );
107
110
 
108
111
  this.scanner = new Scanner();
109
- // 模块信息列表 { name: '', sort: 0, available: true, enabled: true }
110
- this.infos = [];
111
112
  // 模块
112
113
  this.mods = mods;
114
+ // 不使用注册表时,用内部缓存记录模块条目信息
115
+ this.infos = [];
113
116
  if (Drive) {
114
117
  this.Drive = Drive;
115
118
  }
116
119
  }
117
-
118
- get list() {
119
- return this.getList();
120
- }
121
120
  }
122
121
 
123
122
  /**
@@ -128,52 +127,16 @@ Manager.prototype.getEventer = function () {
128
127
  return $.eventer;
129
128
  };
130
129
 
131
- /**
132
- * 获取所有模块信息
133
- * @returns {object[]} 模块信息数组
134
- */
135
- Manager.prototype.getInfos = function () {
136
- return this.infos;
137
- };
138
-
139
- /**
140
- * 创建模块状态模型
141
- * @param {string} name 模块名
142
- * @param {number} sort 排序值
143
- * @param {boolean} state 状态
144
- * @param {string} file 文件名
145
- * @returns {object} 模块状态模型
146
- */
147
- Manager.prototype.newInfo = function (name, sort, state, file = '') {
148
- return {
149
- name,
150
- sort,
151
- state,
152
- enabled: true,
153
- file: file || '',
154
- get available() {
155
- return this.state == true && this.enabled;
156
- }
157
- };
130
+ Manager.prototype.getParentKey = function () {
131
+ return this.constructor.name + '_' + this.name;
158
132
  };
159
133
 
160
134
  /**
161
- * 设置模块信息
162
- * @param {object} info 模块信息
135
+ * 获取所有模块信息
136
+ * @returns {object[]} 模块配置数组
163
137
  */
164
- Manager.prototype.setInfo = function (info) {
165
- let has = false;
166
- for (let i = 0; i < this.infos.length; i++) {
167
- let o = this.infos[i];
168
- if (o.name == info.name) {
169
- this.infos[i] = info;
170
- has = true;
171
- break;
172
- }
173
- }
174
- if (!has) {
175
- this.infos.push(info);
176
- }
138
+ Manager.prototype.getInfos = function () {
139
+ return this._getInfos();
177
140
  };
178
141
 
179
142
  /**
@@ -182,21 +145,20 @@ Manager.prototype.setInfo = function (info) {
182
145
  * @returns {object[]} 模块对象数组
183
146
  */
184
147
  Manager.prototype.getList = function (keyword) {
185
- let list = [];
186
- for (let i = 0; i < this.infos.length; i++) {
187
- let info = this.infos[i];
188
- let mod = this.getMod(info.name);
189
- if (!mod) {
190
- continue;
191
- }
192
- mod.config.state = info.state;
193
- list.push(mod);
194
- }
148
+ let entries = this._getInfos();
149
+
150
+ // 先用 entry 做关键词过滤,避免无效实例化
195
151
  if (keyword) {
196
- list = list.filter(
197
- (o) =>
198
- o.name.includes(keyword) || o.title.includes(keyword) || o.description.includes(keyword)
199
- );
152
+ entries = entries.filter((o) => {
153
+ return o.name.includes(keyword) || o.title.includes(keyword) || o.description.includes(keyword);
154
+ });
155
+ }
156
+
157
+ var list = [];
158
+ for (var i = 0; i < entries.length; i++) {
159
+ var mod = this.getMod(entries[i].name);
160
+ if (!mod) continue;
161
+ list.push(mod);
200
162
  }
201
163
  return list;
202
164
  };
@@ -226,33 +188,19 @@ Manager.prototype.Drive = Drive;
226
188
  * 更新模块信息
227
189
  */
228
190
  Manager.prototype.updateInfo = function () {
229
- this.infos = [];
230
- let mods = this.getMods();
231
- for (let name in mods) {
232
- let o = mods[name];
233
- let info = this.newInfo(name, o.config.sort, o.config.state, o.config_file);
234
- this.infos.push(info);
235
- }
236
- this.sort();
237
- };
238
-
239
- /**
240
- * 排序
241
- */
242
- Manager.prototype._sort = function () {
243
- var sort_key = this.config.sort_key || 'sort';
244
- this.infos.sort((o1, o2) => {
245
- let p1 = o1[sort_key] || 100;
246
- let p2 = o2[sort_key] || 100;
247
- return p1 - p2;
248
- });
191
+ // 由 registry 管理模块信息,无需额外操作
249
192
  };
250
193
 
251
194
  /**
252
- * 排序
195
+ * 获取模块配置列表
196
+ * 启用注册表时从 registry 获取;否则从内部缓存 infos 读取
197
+ * @returns {Array} 排序后的模块配置数组
253
198
  */
254
- Manager.prototype.sort = function () {
255
- this._sort();
199
+ Manager.prototype._getInfos = function () {
200
+ if (this.config.use_registry) {
201
+ return $.registry.getMods(this.getParentKey());
202
+ }
203
+ return this.infos || [];
256
204
  };
257
205
 
258
206
  // ==== 模块管理接口 ====
@@ -263,6 +211,10 @@ Manager.prototype.clearMods = function () {
263
211
  for (let name in this.mods) {
264
212
  delete this.mods[name];
265
213
  }
214
+ // 同步清理内部缓存
215
+ if (!this.config.use_registry && this.infos) {
216
+ this.infos = [];
217
+ }
266
218
  };
267
219
 
268
220
  /**
@@ -274,6 +226,10 @@ Manager.prototype.delMod = function (name) {
274
226
  let mod = this.mods[name];
275
227
  if (mod) {
276
228
  delete this.mods[name];
229
+ // 同步清理内部缓存
230
+ if (!this.config.use_registry && this.infos) {
231
+ this.infos = this.infos.filter((o) => { return o.name !== name; });
232
+ }
277
233
  }
278
234
  return mod;
279
235
  };
@@ -291,11 +247,34 @@ Manager.prototype.setMod = function (name, mod) {
291
247
 
292
248
  /**
293
249
  * 获取模块
250
+ * 内存不存在时,若启用注册表则从注册表配置按需实例化
294
251
  * @param {string} name 模块名
295
- * @returns {object|null} 模块对象,若模块则返回模块对象,否则返回null
252
+ * @returns {object|null} 模块对象
296
253
  */
297
254
  Manager.prototype.getMod = function (name) {
298
- return this.mods[name];
255
+ var mod = this.mods[name];
256
+ if (mod) return mod;
257
+
258
+ // 注册表回退:通过 _getInfos 查找配置并按需实例化
259
+ if (this.config.use_registry) {
260
+ var entries = this._getInfos();
261
+ for (var i = 0; i < entries.length; i++) {
262
+ if (entries[i].name === name) {
263
+ var entry = entries[i];
264
+ const ModClass = this.config.mod_type === 'script' ? Mod : this.Drive;
265
+ mod = new ModClass(entry, this);
266
+ mod.mode = this.config.mode;
267
+ mod.config_file = entry.config_file;
268
+ if (mod._preset) {
269
+ mod._preset();
270
+ }
271
+ this.mods[name] = mod;
272
+ return mod;
273
+ }
274
+ }
275
+ }
276
+
277
+ return null;
299
278
  };
300
279
 
301
280
  /**
@@ -360,47 +339,17 @@ Manager.prototype.newMod = function (config_file, config, script) {
360
339
  * @param {object} script 模块对象
361
340
  * @returns {object} 模块对象
362
341
  */
363
- Manager.prototype.registerMod = function (config_file, config = {}, script = {}) {
342
+ Manager.prototype.regMod = function (config_file, config = {}, script = {}) {
364
343
  let cg = { ...config };
365
- // 未传 config 时尝试从 registry 缓存获取
366
- if (!cg || !cg.name) {
367
- var cached = this._getRegistryConfig(config_file);
368
- if (cached) {
369
- cg = cached;
370
- }
371
- }
372
-
373
- // 处理数组配置:多模块共用一个配置文件(如 event.json 包含多个事件配置)
374
- if (!cg || !cg.name) {
375
- try {
376
- var text = config_file.loadText();
377
- if (text && text.trim().startsWith('[')) {
378
- var arr = $.loadJson(config_file);
379
- if (Array.isArray(arr)) {
380
- for (var i = 0; i < arr.length; i++) {
381
- this.registerMod(config_file, arr[i], script);
382
- }
383
- return;
384
- }
385
- }
386
- } catch (e) {
387
- // 解析失败,交给 newMod 处理(非数组格式或文件不存在)
388
- }
389
- }
390
344
 
391
345
  var mod = this.newMod(config_file, cg, script);
392
346
  if (!mod) return null;
393
347
  this.setMod(mod.config.name, mod);
394
348
 
395
349
  // 启用注册表时,自动写入 $.registry 供后续实例复用
396
- if (this.config.use_registry && $.registry) {
397
- var list = $.registry.module_list;
398
- var has = list.some(function (o) {
399
- return o.name === mod.config.name;
400
- });
401
- if (!has) {
402
- // 用管理器自身的 name 作为 parent 标签,实现多 Manager 隔离
403
- var parent_name = mod.config.parent || this.config.name;
350
+ if (this.config.use_registry) {
351
+ // 直接通过 registry 的 getMod 判断是否已存在,避免 _getInfos 重复
352
+ if (!$.registry.getMod(this.getParentKey(), mod.config.name)) {
404
353
  var entry = {
405
354
  name: mod.config.name,
406
355
  title: mod.config.title,
@@ -409,15 +358,32 @@ Manager.prototype.registerMod = function (config_file, config = {}, script = {})
409
358
  state: mod.config.state,
410
359
  config_file: config_file,
411
360
  main: mod.config.main || '',
412
- scope: mod.config.scope || '',
413
- class_name: mod.config.class_name || 'Drive',
414
- parent: parent_name,
415
- dir: this.config.dir || ''
361
+ class_name: this.config.class_name || 'Drive'
416
362
  };
417
- list.push(entry);
418
- // 同步 registry 的内部缓存,确保 Index.getModule() 可查
419
- $.registry.registerModule(entry);
363
+ // 获取触发键
364
+ let trigger = this.config.trigger;
365
+ if (trigger && trigger.length > 0) {
366
+ for (let t of trigger) {
367
+ entry.trigger[t] = mod.config[t];
368
+ }
369
+ }
370
+ // 用管理器自身的 name 作为 parent 标签,实现多 Manager 隔离
371
+ // 同步 registry 的内部缓存,确保 Index.getMod() 可查
372
+ $.registry.setMod(this.getParentKey(), mod.config.name, entry);
420
373
  }
374
+ } else {
375
+ // 不使用注册表时,写入内部缓存
376
+ var entry = {
377
+ name: mod.config.name,
378
+ title: mod.config.title,
379
+ description: mod.config.description,
380
+ sort: mod.config.sort,
381
+ state: mod.config.state,
382
+ config_file: config_file,
383
+ main: mod.config.main || '',
384
+ class_name: this.config.class_name || 'Drive'
385
+ };
386
+ this.infos.push(entry);
421
387
  }
422
388
 
423
389
  return mod;
@@ -467,7 +433,7 @@ Manager.prototype.reloadMod = async function (name) {
467
433
  * @param {string} name 模块名
468
434
  * @returns {Promise<any>} 注销结果
469
435
  */
470
- Manager.prototype.unregisterMod = async function (name) {
436
+ Manager.prototype.unregMod = async function (name) {
471
437
  let mod = this.getMod(name);
472
438
  if (mod) {
473
439
  // 按生命周期顺序停止→卸载,避免状态机拦截
@@ -484,9 +450,9 @@ Manager.prototype.unregisterMod = async function (name) {
484
450
  * @param {object} config 配置项
485
451
  * @param {object} script 模块对象
486
452
  */
487
- Manager.prototype.registerMods = function (files, config = {}, script = {}) {
453
+ Manager.prototype.regMods = function (files, config = {}, script = {}) {
488
454
  for (let file of files) {
489
- this.registerMod(file, config, script);
455
+ this.regMod(file, config, script);
490
456
  }
491
457
  };
492
458
 
@@ -529,12 +495,12 @@ Manager.prototype.loadScripts = async function () {
529
495
  /**
530
496
  * 更新配置前的钩子函数
531
497
  */
532
- Manager.prototype.updateBefore = function () {};
498
+ Manager.prototype.updateBefore = function () { };
533
499
 
534
500
  /**
535
501
  * 更新配置前的钩子函数
536
502
  */
537
- Manager.prototype.updateAfter = function () {};
503
+ Manager.prototype.updateAfter = function () { };
538
504
 
539
505
  /**
540
506
  * 更新配置
@@ -545,13 +511,11 @@ Manager.prototype.update = async function (dir, clear = true) {
545
511
  try {
546
512
  if (clear) {
547
513
  this.clearMods();
548
- this.infos = [];
549
514
  }
550
515
 
551
516
  var search_dir = dir || this.config.dir;
552
517
  var files = await this._findFiles(search_dir);
553
- this.registerMods(files);
554
- this.updateInfo();
518
+ this.regMods(files);
555
519
 
556
520
  if (!this.config.lazy_load) {
557
521
  await this.loadScripts();
@@ -563,84 +527,34 @@ Manager.prototype.update = async function (dir, clear = true) {
563
527
  };
564
528
 
565
529
  /**
566
- * 从 registry 缓存中查找匹配配置文件的模块配置
567
- * 使用 Map 索引避免每次 O(n) 扫描
568
- * @param {string} config_file 配置文件路径
569
- * @returns {object|null} 模块配置项
570
- */
571
- Manager.prototype._getRegistryConfig = function (config_file) {
572
- var registry = $.registry;
573
- if (!registry || !registry.module_list) return null;
574
-
575
- // 懒构建 config_file → config 的 Map 索引
576
- if (!registry._config_map) {
577
- registry._config_map = {};
578
- var list = registry.module_list;
579
- for (var i = 0; i < list.length; i++) {
580
- var entry = list[i];
581
- registry._config_map[entry.config_file] = entry;
582
- }
583
- }
584
- return registry._config_map[config_file] || null;
585
- };
586
-
587
- /**
588
- * 从 registry 缓存加载模块(按 parent 和 dir 字段匹配)
589
- * 内联创建模块并构建 infos,避免 registerMod/_getRegistryConfig/updateInfo 的冗余循环
590
- * @param {string} parent 父级标识,空或不传时加载所有模块
591
- * @param {string} dir 目录路径,用于区分不同目录下的同名管理器(如 agent 的 user/contact/record)
530
+ * 从 registry 缓存加载模块(按 parent 字段匹配)
531
+ * 从 registry.mod_dict 中按 parent 过滤并创建模块实例
592
532
  * @returns {boolean} 是否加载到模块
593
533
  */
594
- Manager.prototype._loadFromRegistry = function (parent, dir) {
595
- var registry = $.registry;
596
- if (!registry || !registry.module_list || !registry.module_list.length) return false;
534
+ Manager.prototype._loadFromRegistry = function () {
535
+ let lt = this._getInfos();
536
+ if (!lt.length) return false;
597
537
 
598
- var ModClass = this.config.mod_type === 'script' ? Mod : this.Drive;
538
+ var mod_class = this.config.mod_type === 'script' ? Mod : this.Drive;
599
539
  var mode = this.config.mode;
600
- var sort_key = this.config.sort_key || 'sort';
601
- var list = registry.module_list;
602
540
  var mods = this.mods;
603
- var infos = this.infos;
604
- var count = 0;
605
-
606
- for (var i = 0; i < list.length; i++) {
607
- var entry = list[i];
608
- // 按 parent 字段匹配,不传或空时加载所有
609
- if (parent && entry.parent !== parent) continue;
610
- // 按 dir 字段匹配,确保不同目录的管理器互不干扰
611
- if (dir && entry.dir !== dir) continue;
612
-
613
- var config = entry;
614
- var mod = new ModClass(config, this);
615
- mod.mode = mode;
616
- mod.config_file = entry.config_file;
617
- if (mod._preset) {
618
- mod._preset();
619
- }
620
- mods[config.name] = mod;
621
- infos.push({
622
- name: config.name,
623
- sort: config.sort || 100,
624
- state: config.state,
625
- enabled: true,
626
- file: entry.config_file || '',
627
- get available() {
628
- return this.state == true && this.enabled;
629
- }
630
- });
631
- count++;
632
- }
633
541
 
634
- // 排序 infos
635
- if (count > 0) {
636
- infos.sort(function (o1, o2) {
637
- var p1 = o1[sort_key] || 100;
638
- var p2 = o2[sort_key] || 100;
639
- return p1 - p2;
640
- });
542
+ for (var i = 0; i < lt.length; i++) {
543
+ var entry = lt[i];
544
+
545
+ if (!this.config.lazy_load) {
546
+ // 非懒加载模式:立即实例化
547
+ var mod = new ModClass(entry, this);
548
+ mod.mode = mode;
549
+ mod.config_file = entry.config_file;
550
+ if (mod._preset) {
551
+ mod._preset();
552
+ }
553
+ mods[entry.name] = mod;
554
+ }
641
555
  }
642
556
 
643
- return count > 0;
557
+ return true;
644
558
  };
645
559
 
646
560
  /**
@@ -674,8 +588,21 @@ Manager.prototype._findFiles = async function (dir) {
674
588
  Manager.prototype.main = async function (name, method, ...params) {
675
589
  var result = null;
676
590
  if (name) {
677
- let mod = this.getMod(name);
678
- if (mod && mod.config?.state === 1) {
591
+ var mod = this.mods[name];
592
+ // 注册表模式下一次遍历查 entry,避免 getMod 重复 _getInfos
593
+ if (!mod && this.config.use_registry) {
594
+ var entries = this._getInfos();
595
+ var entry = entries.find((o) => { return o.name === name; });
596
+ if (entry && entry.state === 1) {
597
+ var mod_class = this.config.mod_type === 'script' ? Mod : this.Drive;
598
+ mod = new ModClass(entry, this);
599
+ mod.mode = this.config.mode;
600
+ mod.config_file = entry.config_file;
601
+ if (mod._preset) mod._preset();
602
+ this.mods[name] = mod;
603
+ }
604
+ }
605
+ if (mod) {
679
606
  result = await this._runMod(mod, method, ...params);
680
607
  }
681
608
  } else if (name === null) {
@@ -693,22 +620,26 @@ Manager.prototype.main = async function (name, method, ...params) {
693
620
  */
694
621
  Manager.prototype._runAllEnabled = async function (method, ...params) {
695
622
  var result;
696
- for (let i = 0; i < this.infos.length; i++) {
697
- let config = this.infos[i];
698
- let mod = this.getMod(config.name);
699
- if (mod && mod.config?.state === 1) {
700
- var ret = null;
701
- try {
702
- ret = await this._runMod(mod, method, ...params);
703
- } catch (err) {
704
- this.log('error', `执行模块方法失败: `, err);
705
- }
706
- if (ret !== null && ret !== undefined) {
707
- result = ret;
708
- // 如果结果不为空且有结束标志,则停止迭代
709
- if (mod.config?.end) {
710
- break;
711
- }
623
+ var entries = this._getInfos();
624
+ for (var i = 0; i < entries.length; i++) {
625
+ var entry = entries[i];
626
+ // 直接用 entry.state 过滤,避免无效实例化
627
+ if (entry.state !== 1) continue;
628
+
629
+ var mod = this.getMod(entry.name);
630
+ if (!mod) continue;
631
+
632
+ var ret = null;
633
+ try {
634
+ ret = await this._runMod(mod, method, ...params);
635
+ } catch (err) {
636
+ this.log('error', `执行模块方法失败: `, err);
637
+ }
638
+ if (ret !== null && ret !== undefined) {
639
+ result = ret;
640
+ // 如果结果不为空且有结束标志,则停止迭代
641
+ if (mod.config?.end) {
642
+ break;
712
643
  }
713
644
  }
714
645
  }
@@ -752,7 +683,7 @@ Manager.prototype._runMod = async function (mod, method, ...params) {
752
683
  /**
753
684
  * 初始化管理器
754
685
  */
755
- Manager.prototype._initManager = function () {};
686
+ Manager.prototype._initManager = function () { };
756
687
 
757
688
  /**
758
689
  * 获取二次开发模块目录
@@ -765,37 +696,43 @@ Manager.prototype.getDir = function () {
765
696
 
766
697
  /**
767
698
  * 加载资源
768
- * 启用注册表时优先从 $.registry.module_list 读取,跳过文件系统扫描
699
+ * 启用注册表时优先从注册表读取,快速启动;
700
+ * 同时在后台异步扫描文件系统,确保注册表数据为物理最新。
769
701
  */
770
702
  Manager.prototype._loadSources = async function () {
771
- var base_dir = this.getBaseDir();
772
- var dir = this.getDir();
773
-
774
703
  // 启用注册表且有缓存数据时,走内存快路径
775
704
  // 按管理器自身 name 过滤,多 Manager 共享 $.registry 时互不污染
776
- if (
777
- this.config.use_registry &&
778
- $.registry &&
779
- $.registry.module_list &&
780
- $.registry.module_list.length > 0
781
- ) {
705
+ if (this.config.use_registry) {
782
706
  // 只有从注册表成功加载到模块时才跳过文件系统扫描,否则回退到文件系统
783
- if (this._loadFromRegistry(this.config.name, this.config.dir)) {
784
- this.updateInfo();
707
+ if (this._loadFromRegistry()) {
708
+ // 后台异步扫描文件系统,确保物理最新
709
+ setImmediate(() => this._scanForUpdate());
785
710
  return;
786
711
  }
787
712
  }
788
713
 
789
- // 无注册表缓存或注册表无匹配模块,走文件系统扫描
790
- if (base_dir) {
791
- // base_dir 和 dir 并行扫描,互不依赖
792
- await Promise.all([this.call('update', base_dir, true), this.call('update', dir, false)]);
793
- } else {
794
- await this.call('update', dir, true);
795
- }
796
- // 文件扫描完成后持久化注册表,确保后续启动可从注册表加载跳过文件扫描
797
- if ($.registry) {
798
- $.registry.save();
714
+ // 注册表无匹配,走文件系统扫描
715
+ await this._scanForUpdate();
716
+ };
717
+
718
+ /**
719
+ * 后台扫描文件系统并同步到注册表
720
+ * 不阻塞启动,让注册表始终与磁盘保持同步
721
+ */
722
+ Manager.prototype._scanForUpdate = async function () {
723
+ var base_dir = this.getBaseDir();
724
+ var dir = this.getDir();
725
+ try {
726
+ if (base_dir) {
727
+ await Promise.all([this.call('update', base_dir, true), this.call('update', dir, false)]);
728
+ } else {
729
+ await this.call('update', dir, true);
730
+ }
731
+ if (this.config.use_registry) {
732
+ $.registry.save();
733
+ }
734
+ } catch (err) {
735
+ this.log('error', '后台扫描同步失败', err);
799
736
  }
800
737
  };
801
738
 
@@ -882,14 +819,11 @@ Manager.prototype._ensureModLoaded = async function (name) {
882
819
  * @returns {Promise} 加载完成
883
820
  */
884
821
  Manager.prototype._ensureAllLoaded = async function () {
885
- var infos = this.getInfos();
886
822
  var promises = [];
823
+ var entries = this._getInfos();
887
824
 
888
- for (var i = 0; i < infos.length; i++) {
889
- var info = infos[i];
890
- promises.push(
891
- this._ensureModLoaded(info.name)
892
- );
825
+ for (var i = 0; i < entries.length; i++) {
826
+ promises.push(this._ensureModLoaded(entries[i].name));
893
827
  }
894
828
  await Promise.all(promises);
895
829
  };
@@ -906,11 +840,10 @@ Manager.prototype.runWait = async function (method, ...params) {
906
840
  }
907
841
 
908
842
  let result;
909
- let infos = this.getInfos();
843
+ var entries = this._getInfos();
910
844
 
911
- for (let i = 0; i < infos.length; i++) {
912
- let info = infos[i];
913
- let mod = await this._ensureModLoaded(info.name);
845
+ for (var i = 0; i < entries.length; i++) {
846
+ let mod = await this._ensureModLoaded(entries[i].name);
914
847
  if (!mod) continue;
915
848
 
916
849
  try {
@@ -919,7 +852,11 @@ Manager.prototype.runWait = async function (method, ...params) {
919
852
  result = ret;
920
853
  }
921
854
  } catch (error) {
922
- this.log('error', `模块${info.name}执行${method}方法失败`, error);
855
+ this.log(
856
+ 'error',
857
+ '\u6A21\u5757' + entries[i].name + '\u6267\u884C' + method + '\u65B9\u6CD5\u5931\u8D25',
858
+ error
859
+ );
923
860
  }
924
861
  }
925
862
 
@@ -940,15 +877,18 @@ Manager.prototype.runAsync = async function (method, ...params) {
940
877
  // 确保所有模块都已加载
941
878
  await this._ensureAllLoaded();
942
879
 
943
- let infos = this.getInfos();
880
+ var entries = this._getInfos();
944
881
 
945
- for (let i = 0; i < infos.length; i++) {
946
- let info = infos[i];
947
- let mod = this.getMod(info.name);
882
+ for (var i = 0; i < entries.length; i++) {
883
+ var mod = this.mods[entries[i].name];
948
884
  if (!mod) continue;
949
885
 
950
886
  mod.do(method, ...params).catch((error) => {
951
- this.log('error', `模块${info.name}执行${method}方法失败`, error);
887
+ this.log(
888
+ 'error',
889
+ '\u6A21\u5757' + entries[i].name + '\u6267\u884C' + method + '\u65B9\u6CD5\u5931\u8D25',
890
+ error
891
+ );
952
892
  });
953
893
  }
954
894
 
@@ -970,11 +910,10 @@ Manager.prototype.runAll = async function (method, ...params) {
970
910
  await this._ensureAllLoaded();
971
911
 
972
912
  const promises = [];
973
- let infos = this.getInfos();
913
+ var entries = this._getInfos();
974
914
 
975
- for (let i = 0; i < infos.length; i++) {
976
- let info = infos[i];
977
- let mod = this.getMod(info.name);
915
+ for (var i = 0; i < entries.length; i++) {
916
+ var mod = this.mods[entries[i].name];
978
917
  if (!mod) continue;
979
918
 
980
919
  promises.push(mod.do(method, ...params));
@@ -998,11 +937,10 @@ Manager.prototype.runRace = async function (method, ...params) {
998
937
  await this._ensureAllLoaded();
999
938
 
1000
939
  const promises = [];
1001
- let infos = this.getInfos();
940
+ var entries = this._getInfos();
1002
941
 
1003
- for (let i = 0; i < infos.length; i++) {
1004
- let info = infos[i];
1005
- let mod = this.getMod(info.name);
942
+ for (var i = 0; i < entries.length; i++) {
943
+ var mod = this.mods[entries[i].name];
1006
944
  if (!mod) continue;
1007
945
 
1008
946
  promises.push(
@@ -1027,11 +965,10 @@ Manager.prototype.runWaterfall = async function (method, result, ...params) {
1027
965
  throw new TypeError('方法名称必须是字符串');
1028
966
  }
1029
967
 
1030
- let infos = this.getInfos();
968
+ var entries = this._getInfos();
1031
969
 
1032
- for (let i = 0; i < infos.length; i++) {
1033
- let info = infos[i];
1034
- let mod = await this._ensureModLoaded(info.name);
970
+ for (var i = 0; i < entries.length; i++) {
971
+ var mod = await this._ensureModLoaded(entries[i].name);
1035
972
  if (!mod) continue;
1036
973
 
1037
974
  try {
@@ -1040,7 +977,11 @@ Manager.prototype.runWaterfall = async function (method, result, ...params) {
1040
977
  result = ret;
1041
978
  }
1042
979
  } catch (error) {
1043
- this.log('error', `模块${info.name}执行${method}方法失败`, error);
980
+ this.log(
981
+ 'error',
982
+ '\u6A21\u5757' + entries[i].name + '\u6267\u884C' + method + '\u65B9\u6CD5\u5931\u8D25',
983
+ error
984
+ );
1044
985
  }
1045
986
  }
1046
987
 
@@ -1114,7 +1055,7 @@ Manager.prototype.createFile = function (config, file) {
1114
1055
  */
1115
1056
  Manager.prototype.create = function (config, file = '') {
1116
1057
  let f = this.createFile(config, file);
1117
- let mod = this.registerMod(f, config);
1058
+ let mod = this.regMod(f, config);
1118
1059
  return mod;
1119
1060
  };
1120
1061
 
@@ -1128,7 +1069,7 @@ Manager.prototype.remove = async function (name) {
1128
1069
  if (mod) {
1129
1070
  await mod.remove();
1130
1071
  }
1131
- await this.unregisterMod(name);
1072
+ await this.unregMod(name);
1132
1073
  return mod;
1133
1074
  };
1134
1075
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mm_machine",
3
- "version": "3.1.0",
3
+ "version": "3.1.2",
4
4
  "description": "A flexible Node.js plugin mechanism system for dynamic loading, management and execution of modules. Supports hot reload, lifecycle management, and modern JavaScript features.",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/registry.js CHANGED
@@ -1,3 +1,5 @@
1
+ require('mm_expand');
2
+
1
3
  /**
2
4
  * 注册类 - 注册表模式
3
5
  * 管理模块类的注册、模块配置的持久化、模块实例的懒加载
@@ -14,14 +16,10 @@ class Registry {
14
16
  ...config
15
17
  };
16
18
  this.class_dict = this.getDefaultClassDict();
17
- this.module_list = [];
19
+ this.mod_dict = {};
18
20
 
19
21
  // 注册表缓存:类名 -> 类构造函数
20
- this._class_cache = {};
21
- // 注册表缓存:模块名 -> { config, instance }
22
- this._module_cache = {};
23
- // 类名索引:类名 -> [模块名]
24
- this._class_index = {};
22
+ this.class_cache = {};
25
23
  this._preset();
26
24
  }
27
25
  }
@@ -81,7 +79,7 @@ Registry.prototype.registerClass = function (class_name, class_ref) {
81
79
  if (!class_name || !class_ref) {
82
80
  throw new TypeError('模块类名和类引用不能为空');
83
81
  }
84
- this._class_cache[class_name] = class_ref;
82
+ this.class_cache[class_name] = class_ref;
85
83
  };
86
84
 
87
85
  /**
@@ -90,60 +88,41 @@ Registry.prototype.registerClass = function (class_name, class_ref) {
90
88
  * @returns {Function} 模块类构造函数
91
89
  */
92
90
  Registry.prototype.getClass = function (class_name) {
93
- return this._class_cache[class_name];
94
- };
95
-
96
- /**
97
- * 注册模块配置到缓存(不实例化)
98
- * @param {object} config 模块配置项
99
- * @returns {object} 注册的配置项
100
- * @throws {Error} 模块配置项错误
101
- */
102
- Registry.prototype.registerModule = function (config) {
103
- if (!config) {
104
- throw new TypeError('模块配置不能为空');
105
- }
106
- if (!config.name) {
107
- throw new TypeError('模块名称不能为空');
108
- }
109
- var class_name = config.class_name || 'Drive';
110
- this._module_cache[config.name] = {
111
- config: config,
112
- instance: null
113
- };
114
- // 按类名建立索引
115
- if (!this._class_index[class_name]) {
116
- this._class_index[class_name] = [];
117
- }
118
- this._class_index[class_name].push(config.name);
119
- return config;
91
+ return this.class_cache[class_name];
120
92
  };
121
-
122
93
  /**
123
94
  * 获取模块实例(懒加载)
124
95
  * 首次调用时根据 config 和已注册的类构造函数实例化
125
96
  * @param {string} name 模块名
126
97
  * @returns {object|null} 模块实例
127
98
  */
128
- Registry.prototype.getModule = function (name) {
129
- var entry = this._module_cache[name];
130
- if (!entry) return null;
131
-
132
- if (!entry.instance) {
133
- var class_name = entry.config.class_name || 'Drive';
134
- const CS = this._class_cache[class_name];
135
- if (!CS) {
136
- console.error('模块类 ' + class_name + ' 未注册');
137
- return null;
138
- }
139
- try {
140
- entry.instance = new CS(entry.config);
141
- } catch (err) {
142
- console.error('实例化模块 ' + name + ' 失败: ' + err.message);
143
- return null;
99
+ Registry.prototype.getMod = function (name) {
100
+ // 从 mod_dict 中查找配置
101
+ var config = null;
102
+ for (var parent in this.mod_dict) {
103
+ var lt = this.mod_dict[parent];
104
+ for (var i = 0; i < lt.length; i++) {
105
+ if (lt[i].name === name) {
106
+ config = lt[i];
107
+ break;
108
+ }
144
109
  }
110
+ if (config) break;
111
+ }
112
+ if (!config) return null;
113
+
114
+ var class_name = config.class_name || 'Drive';
115
+ var CS = this.class_cache[class_name];
116
+ if (!CS) {
117
+ console.error('模块类 ' + class_name + ' 未注册');
118
+ return null;
119
+ }
120
+ try {
121
+ return new CS(config);
122
+ } catch (err) {
123
+ console.error('实例化模块 ' + name + ' 失败: ' + err.message);
124
+ return null;
145
125
  }
146
- return entry.instance;
147
126
  };
148
127
 
149
128
  /**
@@ -151,31 +130,21 @@ Registry.prototype.getModule = function (name) {
151
130
  * @param {string} class_name 模块类名
152
131
  * @returns {Array} 模块实例数组
153
132
  */
154
- Registry.prototype.getModules = function (class_name) {
155
- var names = this._class_index[class_name];
156
- if (!names || names.length === 0) return [];
157
- return names.map(function (name) {
158
- return this.getModule(name);
159
- }, this);
160
- };
161
-
162
- /**
163
- * 注销模块
164
- * @param {string} name 模块名
165
- */
166
- Registry.prototype.unregisterModule = function (name) {
167
- var entry = this._module_cache[name];
168
- if (!entry) return;
169
-
170
- var class_name = entry.config.class_name || 'Drive';
171
- var names = this._class_index[class_name];
172
- if (names) {
173
- var idx = names.indexOf(name);
174
- if (idx !== -1) {
175
- names.splice(idx, 1);
133
+ Registry.prototype.getModsFromClass = function (class_name) {
134
+ var result = [];
135
+ for (var parent in this.mod_dict) {
136
+ var lt = this.mod_dict[parent];
137
+ for (var i = 0; i < lt.length; i++) {
138
+ var cfg = lt[i];
139
+ if ((cfg.class_name || 'Drive') === class_name) {
140
+ var instance = this.getMod(cfg.name);
141
+ if (instance) {
142
+ result.push(instance);
143
+ }
144
+ }
176
145
  }
177
146
  }
178
- delete this._module_cache[name];
147
+ return result;
179
148
  };
180
149
 
181
150
  /**
@@ -197,11 +166,12 @@ Registry.prototype.load = function () {
197
166
  }
198
167
  }
199
168
 
200
- // 注册模块配置(仅新增不覆盖,保留已有实例)
201
- for (var i = 0; i < this.module_list.length; i++) {
202
- var mod_cfg = this.module_list[i];
203
- if (!this._module_cache[mod_cfg.name]) {
204
- this.registerModule(mod_cfg);
169
+ // 注册模块配置
170
+ for (var parent in this.mod_dict) {
171
+ var lt = this.mod_dict[parent];
172
+ for (var i = 0; i < lt.length; i++) {
173
+ var mod_cfg = lt[i];
174
+ this.setMod(parent, mod_cfg.name, mod_cfg);
205
175
  }
206
176
  }
207
177
  };
@@ -221,60 +191,77 @@ Registry.prototype.newModel = function () {
221
191
  version: '1.0.0',
222
192
  dependencies: {},
223
193
  sort: 100,
224
- enabled: true,
194
+ state: 1,
225
195
  auto_start: 'auto',
226
196
  class_name: 'Drive',
227
197
  config_file: '',
228
- main: '',
229
- values: {}
198
+ main: ''
230
199
  };
231
200
  };
232
201
 
233
202
  /**
234
203
  * 设置模块
204
+ * @param {string} parent 父级名称
205
+ * @param {string} name 模块名称
235
206
  * @param {object} config 模块配置项
236
207
  * @returns {object} 模块配置项
237
208
  */
238
- Registry.prototype.set = function (config) {
209
+ Registry.prototype.setMod = function (parent, name, config) {
210
+ if (!parent) {
211
+ throw new TypeError('父级名称(parent)不能为空');
212
+ }
213
+ else if (typeof parent !== 'string') {
214
+ throw new TypeError('父级名称(parent)必须为字符串');
215
+ }
216
+ if (!name) {
217
+ throw new TypeError('模块名称(name)不能为空');
218
+ }
219
+ else if (typeof name !== 'string') {
220
+ throw new TypeError('模块名称(name)必须为字符串');
221
+ }
222
+ if (!config) {
223
+ throw new TypeError('模块配置项不能为空');
224
+ }
225
+ else if (typeof config !== 'object') {
226
+ throw new TypeError('模块配置项必须为对象');
227
+ }
239
228
  let cg = this.checkConfig(config);
229
+ cg.parent = parent;
230
+
231
+ // 按 parent 分组存储到 mod_dict
232
+ if (!this.mod_dict[parent]) {
233
+ this.mod_dict[parent] = [];
234
+ }
235
+ var lt = this.mod_dict[parent];
236
+
240
237
  let has = false;
241
- for (let i = 0; i < this.module_list.length; i++) {
242
- let o = this.module_list[i];
243
- if (o.name === cg.name) {
244
- if (o.class_name !== cg.class_name) {
245
- throw new Error('模块类名与配置项类名不一致');
246
- }
247
- this.module_list[i] = cg;
238
+ for (let i = 0; i < lt.length; i++) {
239
+ let o = lt[i];
240
+ if (o.name === name) {
241
+ lt[i] = cg;
248
242
  has = true;
249
243
  break;
250
244
  }
251
245
  }
252
246
  if (!has) {
253
- this.module_list.push(cg);
254
- }
255
- // 同步更新 _module_cache,避免 get() 读到脏数据
256
- if (this._module_cache[cg.name]) {
257
- this._module_cache[cg.name].config = cg;
258
- } else {
259
- this.registerModule(cg);
247
+ lt.push(cg);
260
248
  }
261
- // 清除外部缓存索引
262
- this._config_map = null;
263
249
  return cg;
264
250
  };
265
251
 
266
252
  /**
267
253
  * 获取模块
254
+ * @param {string} parent 父级名称
268
255
  * @param {string} name 模块名称
269
256
  * @returns {object} 模块配置项
270
257
  */
271
- Registry.prototype.get = function (name) {
272
- // 先查缓存索引,无命中再回退线性扫描
273
- var entry = this._module_cache[name];
274
- if (entry) return entry.config;
275
- for (let i = 0; i < this.module_list.length; i++) {
276
- if (this.module_list[i].name === name) {
277
- return this.module_list[i];
258
+ Registry.prototype.getMod = function (parent, name) {
259
+ var lt = this.mod_dict[parent];
260
+ if (lt) {
261
+ for (let i = 0; i < lt.length; i++) {
262
+ if (lt[i].name === name) {
263
+ return lt[i];
264
+ }
278
265
  }
279
266
  }
280
267
  return null;
@@ -282,41 +269,35 @@ Registry.prototype.get = function (name) {
282
269
 
283
270
  /**
284
271
  * 删除模块
272
+ * @param {string} parent 父级名称
285
273
  * @param {string} name 模块名称
286
274
  * @returns {object} 模块配置项
287
275
  */
288
- Registry.prototype.del = function (name) {
289
- let obj = null;
290
- for (let i = 0; i < this.module_list.length; i++) {
291
- if (this.module_list[i].name === name) {
292
- obj = this.module_list[i];
293
- this.module_list.splice(i, 1);
276
+ Registry.prototype.delMod = function (parent, name) {
277
+ var lt = this.mod_dict[parent];
278
+ if (!lt) return null;
279
+
280
+ var obj = null;
281
+ for (let i = 0; i < lt.length; i++) {
282
+ if (lt[i].name === name) {
283
+ obj = lt[i];
284
+ lt.splice(i, 1);
294
285
  break;
295
286
  }
296
287
  }
297
- // 同步清理内存缓存,避免 get() 读到已删除数据
298
- if (obj) {
299
- var class_name = obj.class_name || 'Drive';
300
- var names = this._class_index[class_name];
301
- if (names) {
302
- var idx = names.indexOf(name);
303
- if (idx !== -1) {
304
- names.splice(idx, 1);
305
- }
306
- }
307
- delete this._module_cache[name];
288
+ if (lt.length === 0) {
289
+ delete this.mod_dict[parent];
308
290
  }
309
- // 清除外部缓存索引
310
- this._config_map = null;
311
291
  return obj;
312
292
  };
313
293
 
314
294
  /**
315
295
  * 获取模块列表
296
+ * @param {string} parent 父级名称
316
297
  * @returns {Array} 模块配置项数组
317
298
  */
318
- Registry.prototype.getList = function () {
319
- return this.module_list;
299
+ Registry.prototype.getMods = function (parent) {
300
+ return this.mod_dict[parent] || [];
320
301
  };
321
302
 
322
303
  /**
@@ -328,21 +309,17 @@ Registry.prototype.getList = function () {
328
309
  Registry.prototype.checkConfig = function (config) {
329
310
  let cg = { ...this.newModel(), ...config };
330
311
  let {
331
- parent,
332
312
  name,
333
313
  title,
334
314
  description,
335
315
  version,
336
- enabled,
316
+ state,
337
317
  auto_start,
338
318
  class_name,
339
319
  config_file,
340
320
  main,
341
321
  dependencies
342
322
  } = cg;
343
- if (!parent) {
344
- cg.parent = '';
345
- }
346
323
  if (!name) {
347
324
  throw new TypeError('模块名称不能为空');
348
325
  }
@@ -359,34 +336,42 @@ Registry.prototype.checkConfig = function (config) {
359
336
  if (valid_auto.indexOf(auto_start) === -1 && ![true, false].includes(auto_start)) {
360
337
  throw new TypeError('模块自动启动配置错误,只能为true、false、auto');
361
338
  }
362
- if (!this.class_dict[class_name]) {
339
+ if (!this.class_cache[class_name]) {
363
340
  throw new TypeError('模块类不存在');
364
341
  }
365
- if (!enabled) {
366
- cg.enabled = false;
367
- } else if (enabled === 'true') {
368
- cg.enabled = true;
369
- }
370
342
  if (!version) {
371
343
  cg.version = '1.0.0';
372
344
  }
373
345
  if (!main) {
374
346
  cg.main = '';
375
347
  }
348
+ if (state) {
349
+ cg.state = 1;
350
+ }
351
+ else {
352
+ cg.state = 0;
353
+ }
376
354
  if (!dependencies) {
377
355
  cg.dependencies = {};
378
356
  }
379
357
  return cg;
380
358
  };
381
359
 
360
+ /**
361
+ * 获取注册表目录
362
+ * @returns {string} 注册表目录
363
+ */
364
+ Registry.prototype.getDir = function () {
365
+ return this.config.dir.fullname();
366
+ };
367
+
382
368
  /**
383
369
  * 获取模块类文件
384
- * @param {string} class_name 模块类名
385
370
  * @returns {string} 模块类文件路径
386
371
  */
387
- Registry.prototype.getClassFile = function (class_name) {
372
+ Registry.prototype.getClassFile = function () {
388
373
  let file_name = this.config.name + '_class.json';
389
- let file = file_name.fullname(this.config.dir);
374
+ let file = file_name.fullname(this.getDir());
390
375
  // file.addDir();
391
376
  return file;
392
377
  };
@@ -395,9 +380,9 @@ Registry.prototype.getClassFile = function (class_name) {
395
380
  * 获取模块文件
396
381
  * @returns {string} 模块文件路径
397
382
  */
398
- Registry.prototype.getModuleFile = function () {
383
+ Registry.prototype.getModFile = function () {
399
384
  let file_name = this.config.name + '_module.json';
400
- let file = file_name.fullname(this.config.dir);
385
+ let file = file_name.fullname(this.getDir());
401
386
  // file.addDir();
402
387
  return file;
403
388
  };
@@ -408,7 +393,7 @@ Registry.prototype.getModuleFile = function () {
408
393
  */
409
394
  Registry.prototype.read = function () {
410
395
  this.class_dict = this.getClassFile().loadJson() || this.getDefaultClassDict();
411
- this.module_list = this.getModuleFile().loadJson() || [];
396
+ this.mod_dict = this.getModFile().loadJson() || {};
412
397
  };
413
398
 
414
399
  /**
@@ -419,7 +404,7 @@ Registry.prototype.read = function () {
419
404
  Registry.prototype.save = function () {
420
405
  try {
421
406
  this.getClassFile().saveJson(this.class_dict);
422
- this.getModuleFile().saveJson(this.module_list);
407
+ this.getModFile().saveJson(this.mod_dict);
423
408
  } catch (err) {
424
409
  console.error('保存注册数据失败: ' + err.message);
425
410
  }
@@ -429,20 +414,24 @@ Registry.prototype.save = function () {
429
414
  * 排序模块
430
415
  */
431
416
  Registry.prototype.sort = function () {
432
- this.module_list.sort((a, b) => {
433
- if (a.parent !== b.parent) {
434
- return a.parent.localeCompare(b.parent);
435
- }
436
- if (a.sort !== b.sort) {
437
- return a.sort - b.sort;
438
- }
439
- if (a.name !== b.name) {
440
- return a.name.localeCompare(b.name);
441
- }
442
- return 0;
443
- });
417
+ for (var parent in this.mod_dict) {
418
+ this.mod_dict[parent].sort((a, b) => {
419
+ if (a.sort !== b.sort) {
420
+ return a.sort - b.sort;
421
+ }
422
+ if (a.name !== b.name) {
423
+ return a.name.localeCompare(b.name);
424
+ }
425
+ return 0;
426
+ });
427
+ }
444
428
  };
445
429
 
430
+
431
+ if (!$.registry) {
432
+ $.registry = new Registry({ name: 'default' });
433
+ }
434
+
446
435
  module.exports = {
447
436
  Registry
448
437
  };