mm_machine 3.5.5 → 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,31 +1,6 @@
1
1
  const { Mod: CoreMod } = require('mm_mod');
2
2
  const { saveJson, loadJson } = require('mm_helper');
3
3
 
4
- /**
5
- * 构造模块时使用的占位名称
6
- * @description mm_mod.Mod 要求配置必须包含名称,模块在未指定名称时先用占位名称通过校验,再还原为空名称
7
- * @type {string}
8
- */
9
- const MOD_DEFAULT_NAME = '__mm_machine_mod__';
10
-
11
- /**
12
- * 模块运行状态在状态存储器中的键名
13
- * @type {string}
14
- */
15
- const MOD_STATE_KEY = 'mod';
16
-
17
- /**
18
- * 模块运行状态的默认值
19
- * @type {{state: string, loaded: boolean, inited: boolean}}
20
- */
21
- const MOD_STATE_DEFAULT = { state: 'created', loaded: false, inited: false };
22
-
23
- /**
24
- * 各实例的待写入状态队列,保证同一模块的状态写入按调用顺序串行落库
25
- * @type {WeakMap<Object, Promise>}
26
- */
27
- const MOD_STATE_WRITING = new WeakMap();
28
-
29
4
  /**
30
5
  * 通用模块类
31
6
  * @description 在 mm_mod.Mod 的生命周期、配置与日志能力之上,提供插件式调度(do 流水线)、
@@ -36,8 +11,6 @@ class Mod extends CoreMod {
36
11
  * 配置项
37
12
  */
38
13
  static config = {
39
- // 模块名称(唯一标识)
40
- name: '',
41
14
  // 模块标题(中文名称)
42
15
  title: '',
43
16
  // 模块描述
@@ -56,14 +29,7 @@ class Mod extends CoreMod {
56
29
  * @param {object} parent 父模块
57
30
  */
58
31
  constructor(config = {}, parent) {
59
- const cfg = { ...config };
60
- if (!cfg.name) {
61
- cfg.name = MOD_DEFAULT_NAME;
62
- }
63
- super(cfg, parent);
64
- if (!config.name) {
65
- this.config.name = '';
66
- }
32
+ super(config, parent);
67
33
  if (parent) {
68
34
  this.getParent = function () {
69
35
  return parent;
@@ -76,149 +42,8 @@ class Mod extends CoreMod {
76
42
  // 监听事件
77
43
  this._listen();
78
44
  }
79
-
80
- /**
81
- * 是否已加载
82
- * @param {boolean} bl 是否已加载,缺省时读取当前值
83
- * @returns {Promise<boolean>} 是否已加载
84
- */
85
- async isLoaded(bl) {
86
- if (bl === undefined) {
87
- return (await this._readModState()).loaded;
88
- }
89
- await this._writeModState(bl ? { loaded: true } : { loaded: false, inited: false });
90
- return bl;
91
- }
92
-
93
- /**
94
- * 是否已初始化
95
- * @param {boolean} bl 是否已初始化,缺省时读取当前值
96
- * @returns {Promise<boolean>} 是否已初始化
97
- */
98
- async isInited(bl) {
99
- if (bl === undefined) {
100
- return (await this._readModState()).inited;
101
- }
102
- await this._writeModState({ inited: bl });
103
- return bl;
104
- }
105
45
  }
106
46
 
107
- /**
108
- * 获取运行状态存储器
109
- * @description mm_state_store 经 mm_cache 反向依赖 mm_mod,只能延迟引用以避开循环依赖
110
- * @returns {Object} 状态存储器
111
- * @private
112
- */
113
- Mod.prototype._getModStateStore = function () {
114
- const { stateAdmin } = require('mm_state_store');
115
- return stateAdmin(this._label());
116
- };
117
-
118
- /**
119
- * 读取运行状态
120
- * @returns {Promise<{state: string, loaded: boolean, inited: boolean}>} 运行状态副本
121
- * @private
122
- */
123
- Mod.prototype._readModState = async function () {
124
- const record = await this._getModStateStore().get(MOD_STATE_KEY);
125
- return { ...MOD_STATE_DEFAULT, ...(record || {}) };
126
- };
127
-
128
- /**
129
- * 合并并写入运行状态
130
- * @param {object} patch 需要更新的状态字段
131
- * @returns {Promise<boolean>} 是否写入成功
132
- * @private
133
- */
134
- Mod.prototype._mergeModState = async function (patch) {
135
- const state = await this._readModState();
136
- return await this._getModStateStore().set(MOD_STATE_KEY, { ...state, ...patch });
137
- };
138
-
139
- /**
140
- * 按补丁写入运行状态
141
- * @description 同一实例的写入串行执行,避免同步调用场景下后写被先写覆盖
142
- * @param {object} patch 需要更新的状态字段
143
- * @returns {Promise<boolean>} 是否写入成功
144
- * @private
145
- */
146
- Mod.prototype._writeModState = async function (patch) {
147
- const prev = MOD_STATE_WRITING.get(this) || Promise.resolve();
148
- const next = prev.then(() => this._mergeModState(patch));
149
- MOD_STATE_WRITING.set(
150
- this,
151
- next.catch(() => { })
152
- );
153
- try {
154
- return await next;
155
- } catch (err) {
156
- this.log('error', '写入运行状态失败', err);
157
- return false;
158
- }
159
- };
160
-
161
- /**
162
- * 获取当前状态
163
- * @returns {Promise<string>} 当前状态
164
- */
165
- Mod.prototype.getState = async function () {
166
- return (await this._readModState()).state;
167
- };
168
-
169
- /**
170
- * 设置当前状态
171
- * @param {string} state 状态值
172
- * @returns {Promise<Mod>} 当前实例
173
- */
174
- Mod.prototype.setState = async function (state) {
175
- await this._writeModState({ state });
176
- return this;
177
- };
178
-
179
- /**
180
- * 设置当前状态(兼容 mm_mod 的内部命名)
181
- * @param {string} state 状态值
182
- * @returns {Promise<Mod>} 当前实例
183
- */
184
- Mod.prototype._setState = async function (state) {
185
- return await this.setState(state);
186
- };
187
-
188
- /**
189
- * 是否处于指定状态
190
- * @param {string} state 目标状态
191
- * @returns {Promise<boolean>} 是否处于该状态
192
- */
193
- Mod.prototype.isState = async function (state) {
194
- return (await this.getState()) === state;
195
- };
196
-
197
- /**
198
- * 是否运行中
199
- * @returns {Promise<boolean>} 是否运行中
200
- */
201
- Mod.prototype.isRunning = async function () {
202
- return await this.isState('started');
203
- };
204
-
205
- /**
206
- * 状态断言
207
- * @param {string} expected 预期状态
208
- * @param {string} action 操作名称
209
- * @returns {Promise<Mod>} 当前实例
210
- * @throws {Error} 当前状态与预期不符时
211
- */
212
- Mod.prototype._assertState = async function (expected, action) {
213
- const state = await this.getState();
214
- if (state !== expected) {
215
- throw new Error(
216
- `${this._label()} cannot ${action} in state "${state}", expected "${expected}"`
217
- );
218
- }
219
- return this;
220
- };
221
-
222
47
  /**
223
48
  * 初始化(兼容 mm_expand 行为,生命周期由 do 流水线驱动)
224
49
  * @returns {Promise<Mod>} 当前实例
@@ -340,13 +165,8 @@ Mod.prototype._listen = function () {
340
165
  Mod.prototype._onLoad = function () {
341
166
  // 1. 加载
342
167
  this.on('load:before', async (ctx) => {
343
- await this.setState('loading');
344
168
  await this._loadCore(...ctx.params);
345
169
  });
346
- this.on('load:after', async () => {
347
- await this.setState('loaded');
348
- await this.isLoaded(true);
349
- });
350
170
  };
351
171
 
352
172
  /**
@@ -355,104 +175,47 @@ Mod.prototype._onLoad = function () {
355
175
  Mod.prototype._onInit = function () {
356
176
  // 初始化
357
177
  this.on('init:before', async (ctx) => {
358
- await this.setState('initing');
359
178
  await this._initCore(...ctx.params);
360
179
  });
361
- this.on('init:success', async () => {
362
- await this.isInited(true);
363
- });
364
- this.on('init:after', async () => {
365
- await this.setState('inited');
366
- });
367
180
  };
368
181
 
369
182
  /**
370
183
  * 监听启动事件
371
184
  */
372
185
  Mod.prototype._onStart = function () {
373
- let status_last = 'inited';
374
186
  // 3. 启动
375
187
  this.on('start:before', async (ctx) => {
376
- status_last = await this.getState();
377
- await this.setState('starting');
378
188
  await this._startCore(...ctx.params);
379
189
  });
380
- this.on('start:success', async () => {
381
- await this.setState('started');
382
- });
383
- this.on('start:error', async () => {
384
- await this.setState(status_last);
385
- });
386
190
  };
387
191
 
388
192
  /**
389
193
  * 监听停止事件
390
194
  */
391
195
  Mod.prototype._onStop = function () {
392
- let status_last = 'started';
393
196
  // 4. 停止
394
- this.on('stop:before', async () => {
395
- status_last = await this.getState();
396
- await this.setState('stopping');
397
- });
398
197
  this.on('stop:after', async (ctx) => {
399
198
  await this._stopCore(...ctx.params);
400
199
  });
401
- this.on('stop:success', async () => {
402
- await this.setState('stopped');
403
- });
404
- this.on('stop:error', async () => {
405
- await this.setState(status_last);
406
- });
407
200
  };
408
201
 
409
202
  /**
410
203
  * 监听销毁事件
411
204
  */
412
205
  Mod.prototype._onDestroy = function () {
413
- let status_last = 'stopped';
414
206
  // 销毁
415
- this.on('destroy:before', async () => {
416
- status_last = await this.getState();
417
- await this.setState('destroying');
418
- });
419
- this.on('destroy:check', async (ctx) => {
420
- if (status_last !== 'unloaded') {
421
- await this.setState(status_last);
422
- ctx.error = new Error('销毁前必须先卸载');
423
- }
424
- });
425
207
  this.on('destroy:after', async (ctx) => {
426
208
  await this._destroyCore(...ctx.params);
427
209
  });
428
- this.on('destroy:success', async () => {
429
- await this.setState('disposed');
430
- });
431
- this.on('destroy:error', async () => {
432
- await this.setState(status_last);
433
- });
434
210
  };
435
211
 
436
212
  /**
437
213
  * 监听卸载事件
438
214
  */
439
215
  Mod.prototype._onUnload = function () {
440
- let status_last = 'stopped';
441
216
  // 5. 卸载
442
- this.on('unload:before', async (ctx) => {
443
- status_last = await this.getState();
444
- await this.setState('unloading');
445
- });
446
- this.on('unload:check', async (ctx) => {
447
- if (status_last !== 'stopped') {
448
- status_last = await this.getState();
449
- ctx.error = new Error('卸载前必须先停止');
450
- }
451
- });
452
217
  this.on('unload:after', async (ctx) => {
453
- await this.setState('unloaded');
454
218
  await this._unloadCore(...ctx.params);
455
- await this.isLoaded(false);
456
219
  });
457
220
  };
458
221
 
@@ -556,7 +319,6 @@ Mod.prototype._unloadCore = async function () {
556
319
  Mod.prototype.reload = async function () {
557
320
  try {
558
321
  await this._unloadCore();
559
- await this.isLoaded(false);
560
322
  } catch (err) {
561
323
  this.log('error', '重载失败', err);
562
324
  }
@@ -749,7 +511,7 @@ Mod.prototype._doSuccessProcess = async function (method, ctx) {
749
511
  * @private
750
512
  */
751
513
  Mod.prototype._doAfterProcess = async function (method, ctx) {
752
- // 顺序执行并等待,确保状态变更在本次调度结束前落库
514
+ // 顺序执行并等待,确保后处理在本次调度结束前完成
753
515
  await this.emitWait(method + ':after', ctx);
754
516
  };
755
517
 
@@ -761,7 +523,7 @@ Mod.prototype._doAfterProcess = async function (method, ctx) {
761
523
  */
762
524
  Mod.prototype._doErrorProcess = async function (method, ctx) {
763
525
  if (ctx.error) {
764
- // 顺序执行并等待,确保错误分支中的状态还原在本次调度结束前落库
526
+ // 顺序执行并等待,确保错误处理在本次调度结束前完成
765
527
  await this.emitWait(method + ':error', ctx);
766
528
  this.log('error', `执行方法${method}出错:`, ctx.error);
767
529
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mm_machine",
3
- "version": "3.5.5",
3
+ "version": "3.5.6",
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": {
@@ -40,15 +40,16 @@
40
40
  ],
41
41
  "dependencies": {
42
42
  "@prettier/sync": "^0.6.1",
43
- "mm_config": "^2.5.2",
43
+ "mm_config": "^2.5.3",
44
44
  "mm_hot_reload": "^1.5.3",
45
- "mm_helper": "^1.0.0",
46
- "mm_mod": "^1.0.1",
47
- "mm_tpl": "^2.7.2"
45
+ "mm_helper": "^1.0.3",
46
+ "mm_loader": "^1.1.1",
47
+ "mm_mod": "^1.0.6",
48
+ "mm_tpl": "^2.7.3"
48
49
  },
49
50
  "devDependencies": {
50
- "eslint": "^10.9.1",
51
- "eslint-plugin-jsdoc": "^64.2.1",
51
+ "eslint": "^10.13.0",
52
+ "eslint-plugin-jsdoc": "^65.4.2",
52
53
  "jest": "^30.5.2",
53
54
  "mm_eslint": "^1.7.7"
54
55
  }
package/lib/scanner.js DELETED
@@ -1,225 +0,0 @@
1
- const fs = require('fs');
2
- const { getAllDir, getAllFile } = require('mm_helper');
3
-
4
- // 扫描结果缓存, 按目录mtime与文件mtime校验失效
5
- // 避免多个Manager实例重复遍历同一目录树, 显著提升批量加载速度
6
- const _scanCache = new Map();
7
- const _CACHE_MAX = 200;
8
- // 快速复用窗口: 启动阶段文件树刚扫描过, 短时间内的命中直接复用, 避免每次全量校验目录mtime
9
- const _CACHE_TTL = 2000;
10
-
11
- /**
12
- * 生成扫描缓存键
13
- * @param {string} dir 根目录
14
- * @param {string} keyword 文件搜索关键词
15
- * @param {string} keyword_dir 目录搜索关键词
16
- * @param {Array} ignore 忽略目录数组
17
- * @param {number} max_depth 最大搜索深度
18
- * @returns {string} 缓存键
19
- */
20
- function _cacheKey(dir, keyword, keyword_dir, ignore, max_depth) {
21
- let depth = max_depth === undefined || max_depth === null ? -1 : max_depth;
22
- return (
23
- (dir || '') +
24
- '\u0001' +
25
- (keyword || '') +
26
- '\u0001' +
27
- (keyword_dir || '') +
28
- '\u0001' +
29
- (ignore || []).join(',') +
30
- '\u0001' +
31
- depth
32
- );
33
- }
34
-
35
- /**
36
- * 获取路径mtime毫秒值, 失败返回-1
37
- * @param {string} f 路径
38
- * @returns {number} mtime毫秒值
39
- */
40
- function _getMtime(f) {
41
- try {
42
- return fs.statSync(f).mtimeMs;
43
- } catch {
44
- return -1;
45
- }
46
- }
47
-
48
- /**
49
- * 校验扫描缓存是否有效
50
- * 目录mtime变化表示有新增或删除, 文件mtime变化表示内容修改
51
- * @param {object} cache 缓存对象
52
- * @returns {boolean} 有效返回true
53
- */
54
- function _isCacheValid(cache) {
55
- for (let i = 0; i < cache.dirs.length; i++) {
56
- if (_getMtime(cache.dirs[i]) !== cache.dir_mtimes[i]) {
57
- return false;
58
- }
59
- }
60
- for (let i = 0; i < cache.list.length; i++) {
61
- if (_getMtime(cache.list[i]) !== cache.list_mtimes[i]) {
62
- return false;
63
- }
64
- }
65
- return true;
66
- }
67
-
68
- /**
69
- * 获取扫描缓存
70
- * @param {string} key 缓存键
71
- * @returns {object|null} 有效的缓存对象, 无效返回null
72
- */
73
- function _getCache(key) {
74
- let cache = _scanCache.get(key);
75
- if (!cache) {
76
- return null;
77
- }
78
- let now = Date.now();
79
- // 启动窗口内直接复用, 避免对大量目录做全量mtime校验
80
- if (now - cache.time <= _CACHE_TTL) {
81
- return cache;
82
- }
83
- // 窗口外做mtime校验, 文件或目录变化时重新扫描
84
- if (_isCacheValid(cache)) {
85
- cache.time = now;
86
- return cache;
87
- }
88
- return null;
89
- }
90
-
91
- /**
92
- * 保存扫描缓存
93
- * @param {string} key 缓存键
94
- * @param {Array} list 结果路径数组
95
- * @param {Array} dirs 遍历的目录数组
96
- */
97
- function _setCache(key, list, dirs) {
98
- let dir_mtimes = [];
99
- for (let i = 0; i < dirs.length; i++) {
100
- dir_mtimes.push(_getMtime(dirs[i]));
101
- }
102
- let list_mtimes = [];
103
- for (let i = 0; i < list.length; i++) {
104
- list_mtimes.push(_getMtime(list[i]));
105
- }
106
- if (_scanCache.size >= _CACHE_MAX) {
107
- _scanCache.clear();
108
- }
109
- _scanCache.set(key, {
110
- list: list,
111
- dirs: dirs,
112
- dir_mtimes: dir_mtimes,
113
- list_mtimes: list_mtimes,
114
- time: Date.now()
115
- });
116
- }
117
-
118
- /**
119
- * 扫描类
120
- * 负责按目录或文件名模式检索文件
121
- * @param {Array} ignore 忽略目录数组
122
- * @param {number} max_depth 最大搜索深度
123
- */
124
- class Scanner {
125
- /**
126
- * 构造函数
127
- * @param {Array} ignore 忽略目录数组
128
- * @param {number} max_depth 最大搜索深度
129
- */
130
- constructor(ignore, max_depth = 3) {
131
- this.ignore = ignore || ['node_modules', '.git'];
132
- this.max_depth = max_depth;
133
- }
134
- }
135
-
136
- /**
137
- * 扫描模块(按目录搜索)
138
- * 先找所有匹配 dirname 的子目录,再在每个子目录中找匹配 filename 的文件
139
- * @param {string} dir 根目录
140
- * @param {string} filename 目标文件名
141
- * @param {string} dirname 目标目录名
142
- * @param {Array} ignore 忽略目录数组
143
- * @param {number} max_depth 最大搜索深度 -1表示不限制深度
144
- * @returns {Array} 文件路径数组
145
- */
146
- Scanner.prototype.scan = async function (
147
- dir,
148
- filename,
149
- dirname,
150
- ignore = this.ignore,
151
- max_depth = this.max_depth
152
- ) {
153
- let dirs = await this.scanDir(dir, dirname, ignore, max_depth);
154
- let results = await Promise.all(
155
- dirs.map((d) => {
156
- return this.scanFile(d, filename, ignore, max_depth);
157
- })
158
- );
159
- return results.flat();
160
- };
161
-
162
- /**
163
- * 扫描模块目录(按目录搜索)
164
- * 在指定目录下找所有匹配 dirname 的子目录
165
- * @param {string} dir 根目录
166
- * @param {string} dirname 目标目录名
167
- * @param {Array} ignore 忽略目录数组
168
- * @param {number} max_depth 最大搜索深度 -1表示不限制深度
169
- * @returns {Array} 目录路径数组
170
- */
171
- Scanner.prototype.scanDir = async function (
172
- dir,
173
- dirname,
174
- ignore = this.ignore,
175
- max_depth = this.max_depth
176
- ) {
177
- let key = _cacheKey(dir, undefined, dirname, ignore, max_depth);
178
- let cache = _getCache(key);
179
- if (cache) {
180
- return cache.list.slice();
181
- }
182
- let dirs = getAllDir(dir, dirname, ignore, max_depth);
183
- // 目录快照需包含全部目录(忽略关键词), 才能检测新增目录
184
- let all_dirs = getAllDir(dir, undefined, ignore, max_depth);
185
- _setCache(key, dirs, all_dirs);
186
- return dirs;
187
- };
188
-
189
- /**
190
- * 扫描模块文件(按文件名搜索)
191
- * 在指定目录下找所有匹配 filename 的文件
192
- * @param {string} dir 根目录
193
- * @param {string} filename 目标文件名
194
- * @param {Array} ignore 忽略目录数组
195
- * @param {number} max_depth 最大搜索深度 -1表示不限制深度
196
- * @returns {Array} 文件路径数组
197
- */
198
- Scanner.prototype.scanFile = async function (
199
- dir,
200
- filename,
201
- ignore = this.ignore,
202
- max_depth = this.max_depth
203
- ) {
204
- let key = _cacheKey(dir, filename, undefined, ignore, max_depth);
205
- let cache = _getCache(key);
206
- if (cache) {
207
- return cache.list.slice();
208
- }
209
- let files = getAllFile(dir, filename, undefined, ignore, max_depth);
210
- // 目录快照用于检测新增或删除文件
211
- let all_dirs = getAllDir(dir, undefined, ignore, max_depth);
212
- _setCache(key, files, all_dirs);
213
- return files;
214
- };
215
-
216
- /**
217
- * 清除扫描缓存
218
- */
219
- Scanner.clearCache = function () {
220
- _scanCache.clear();
221
- };
222
-
223
- module.exports = {
224
- Scanner
225
- };