mm_config 2.5.2 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/conf.js ADDED
@@ -0,0 +1,380 @@
1
+ const { Base } = require('mm_mod');
2
+ const { push, fullname, hasFile, loadJson, saveJson } = require('mm_helper');
3
+
4
+ /**
5
+ * 配置字典(私有)
6
+ * @type {object}
7
+ */
8
+ const dict = {};
9
+
10
+ /**
11
+ * 配置类
12
+ * @class
13
+ */
14
+ class Config extends Base {
15
+ /**
16
+ * 配置选项
17
+ * @type {object}
18
+ */
19
+ static config = {
20
+ debounce_time: 0, // 默认不防抖
21
+ pretty: true,
22
+ format: 'json',
23
+ file: ''
24
+ };
25
+
26
+ /**
27
+ * 预设选项
28
+ * @type {object}
29
+ */
30
+ static options = {
31
+
32
+ };
33
+
34
+ /**
35
+ * 创建配置实例
36
+ * @param {object} config - 配置选项
37
+ * @param {number} config.debounce_time - 防抖时间(ms)
38
+ * @param {boolean} config.pretty - 是否美化输出
39
+ * @param {string} config.format - 格式(json/json5)
40
+ * @param {string} config.file - 配置文件路径
41
+ * @param {object} options - 选项
42
+ */
43
+ constructor(config, options = {}) {
44
+ super(config);
45
+ this.options = { ...Config.options, ...options };
46
+ this._promise = Promise.resolve();
47
+ }
48
+ }
49
+
50
+ /**
51
+ * 设置配置
52
+ * @param {object} options - 配置对象
53
+ */
54
+ Config.prototype.setOptions = function (options) {
55
+ push(this.options, options, true);
56
+ };
57
+
58
+ /**
59
+ * 获取配置
60
+ * @returns {object} 配置对象
61
+ */
62
+ Config.prototype.getOptions = function () {
63
+ return this.options;
64
+ };
65
+
66
+ /**
67
+ * 保存配置到文件(同步)
68
+ * @returns {boolean} 保存是否成功
69
+ */
70
+ Config.prototype.saveSync = function () {
71
+ if (!this.config.file) return false;
72
+ try {
73
+ saveJson(this.config.file, this.options);
74
+ return true;
75
+ } catch (err) {
76
+ this.log('error', `Error saving options to ${this.config.file}:`, err.message);
77
+ return false;
78
+ }
79
+ };
80
+
81
+ /**
82
+ * 保存配置到文件(异步)
83
+ * @returns {Promise<boolean>} 保存操作是否成功
84
+ */
85
+ Config.prototype.saveAsync = async function () {
86
+ if (!this.config.file) return Promise.resolve(true);
87
+
88
+ // 确保之前的写操作完成
89
+ await this._promise;
90
+
91
+ this._promise = Promise.resolve()
92
+ .then(() => {
93
+ saveJson(this.config.file, this.options);
94
+ return true;
95
+ })
96
+ .catch(err => {
97
+ this.log('error', `Error saving options to ${this.config.file}:`, err.message);
98
+ return false;
99
+ });
100
+
101
+ return this._promise;
102
+ };
103
+
104
+ /**
105
+ * 获取代理对象
106
+ * @returns {Proxy} 配置对象的代理实例
107
+ */
108
+ Config.prototype.getProxy = function () {
109
+ let self = this;
110
+
111
+ return new Proxy(this.options, {
112
+ set(obj, prop, val) {
113
+ obj[prop] = val;
114
+
115
+ if (self.config.debounce_time > 0) {
116
+ // 防抖处理
117
+ if (self._timer) {
118
+ clearTimeout(self._timer);
119
+ }
120
+ self._timer = setTimeout(() => {
121
+ self.saveSync();
122
+ }, self.config.debounce_time);
123
+ } else {
124
+ // 无防抖,直接保存
125
+ self.saveSync();
126
+ }
127
+
128
+ return true;
129
+ },
130
+
131
+ get(obj, prop) {
132
+ // 提供一些特殊属性访问
133
+ if (prop === '_saveAsync') {
134
+ return () => self.saveAsync();
135
+ }
136
+ if (prop === '_saveSync') {
137
+ return () => self.saveSync();
138
+ }
139
+ if (prop === '_raw') {
140
+ return obj;
141
+ }
142
+
143
+ return obj[prop];
144
+ }
145
+ });
146
+ };
147
+
148
+ /**
149
+ * 获取异步代理对象
150
+ * @returns {Proxy} 异步配置对象的代理实例
151
+ */
152
+ Config.prototype.getAsyncProxy = function () {
153
+ let self = this;
154
+
155
+ return new Proxy(this.options, {
156
+ set(obj, prop, val) {
157
+ obj[prop] = val;
158
+
159
+ if (self.config.debounce_time > 0) {
160
+ if (self._timer) {
161
+ clearTimeout(self._timer);
162
+ }
163
+ self._timer = setTimeout(() => {
164
+ self.saveAsync();
165
+ }, self.config.debounce_time);
166
+ } else {
167
+ self.saveAsync();
168
+ }
169
+
170
+ return true;
171
+ },
172
+
173
+ get(obj, prop) {
174
+ if (prop === '_saveAsync') {
175
+ return () => self.saveAsync();
176
+ }
177
+ if (prop === '_saveSync') {
178
+ return () => self.saveSync();
179
+ }
180
+ if (prop === '_raw') {
181
+ return obj;
182
+ }
183
+
184
+ return obj[prop];
185
+ }
186
+ });
187
+ };
188
+
189
+ /**
190
+ * 获取所有配置项
191
+ * @returns {object} 所有配置项
192
+ */
193
+ Config.prototype.all = function () {
194
+ return this.options;
195
+ };
196
+
197
+ /**
198
+ * 获取配置值
199
+ * @param {string} key - 配置键
200
+ * @returns {*} 配置值
201
+ */
202
+ Config.prototype.get = function (key) {
203
+ return this.options[key];
204
+ };
205
+
206
+ /**
207
+ * 获取配置分节
208
+ * @param {string} [name] - 分节名称,缺省时返回全部配置
209
+ * @returns {object} 配置分节或全部配置
210
+ */
211
+ Config.prototype.conf = function (name) {
212
+ if (name) {
213
+ return this.options[name];
214
+ }
215
+ return this.options;
216
+ };
217
+
218
+ /**
219
+ * 设置配置值
220
+ * @param {string} key - 配置键
221
+ * @param {*} value - 配置值
222
+ */
223
+ Config.prototype.set = function (key, value) {
224
+ this.options[key] = value;
225
+ };
226
+
227
+ /**
228
+ * 更新配置并保存到文件
229
+ * @param {string} [name] - 分节名称,存在时确保该分节存在后保存
230
+ * @returns {boolean} 更新是否成功
231
+ */
232
+ Config.prototype.update = function (name) {
233
+ if (name && this.options[name] === undefined) {
234
+ this.options[name] = {};
235
+ }
236
+ return this.saveSync();
237
+ };
238
+
239
+ /**
240
+ * 检查配置是否存在
241
+ * @param {string} key - 配置键
242
+ * @returns {boolean} 配置项是否存在
243
+ */
244
+ Config.prototype.has = async function (key) {
245
+ return this.options.hasOwnProperty(key);
246
+ };
247
+
248
+ /**
249
+ * 删除配置项
250
+ * @param {string} key - 配置键
251
+ */
252
+ Config.prototype.del = async function (key) {
253
+ delete this.options[key];
254
+ };
255
+
256
+ /**
257
+ * 获取所有配置键
258
+ * @returns {Array<string>} 配置键列表
259
+ */
260
+ Config.prototype.keys = async function () {
261
+ let keys = [];
262
+ let local_keys = Object.keys(this.options);
263
+ keys = keys.concat(local_keys);
264
+ return keys;
265
+ };
266
+
267
+ /**
268
+ * 销毁
269
+ */
270
+ Config.prototype.destroy = function () {
271
+ delete dict[this.config.file];
272
+ };
273
+
274
+ /**
275
+ * 从配置文件加载配置
276
+ * @returns {boolean} 加载是否成功
277
+ */
278
+ Config.prototype.load = function () {
279
+ if (!this.config.file) return false;
280
+ this.options = loadJson(this.config.file) || {};
281
+ };
282
+
283
+ /**
284
+ * 创建配置(同步)
285
+ * @param {string} file - 配置文件路径
286
+ * @param {object} options - 配置对象
287
+ * @param {object} config - 配置选项
288
+ * @returns {Proxy} 配置代理对象
289
+ */
290
+ function create(file, options = {}, config = {}) {
291
+ let f = fullname(file);
292
+ let cfg = new Config({ file: f, ...config }, options);
293
+ if (!hasFile(file)) {
294
+ cfg.saveSync(); // 确保文件存在
295
+ }
296
+ // 注册配置字典
297
+ dict[f] = cfg;
298
+ return dict[f].getProxy();
299
+ }
300
+
301
+ /**
302
+ * 创建配置(异步)
303
+ * @param {string} file - 配置文件路径
304
+ * @param {object} options - 配置对象
305
+ * @param {object} config - 配置选项
306
+ * @returns {Promise<Proxy>} 异步配置代理对象
307
+ */
308
+ async function createAsync(file, options = {}, config = {}) {
309
+ let f = fullname(file);
310
+ let cfg = new Config({ file: f, ...config }, options);
311
+ if (!hasFile(file)) {
312
+ await cfg.saveAsync(); // 确保文件存在
313
+ }
314
+ // 注册配置字典
315
+ dict[f] = cfg;
316
+ return dict[f].getAsyncProxy();
317
+ }
318
+
319
+ /**
320
+ * 清理指定文件配置缓存
321
+ * @param {string} file - 配置文件路径
322
+ * @returns {void}
323
+ */
324
+ function clear(file) {
325
+ if (!file) return clearAll();
326
+ let f = fullname(file);
327
+ if (dict[f]) {
328
+ delete dict[f];
329
+ }
330
+ }
331
+
332
+ /**
333
+ * 清理所有配置缓存
334
+ */
335
+ function clearAll() {
336
+ Object.keys(dict).forEach(key => {
337
+ delete dict[key];
338
+ });
339
+ }
340
+
341
+ /**
342
+ * 获取配置代理对象
343
+ * @param {object} options - 配置对象
344
+ * @param {string} file - 配置文件路径
345
+ * @param {object} config - 配置选项
346
+ * @returns {Proxy} 配置代理对象
347
+ */
348
+ function conf(options, file, config = {}) {
349
+ return create(file, options, config);
350
+ }
351
+
352
+ /**
353
+ * 配置实例单例
354
+ * @type {Config|null}
355
+ */
356
+ let config_instance = null;
357
+
358
+ /**
359
+ * 获取配置单例
360
+ * @param {object} options - 配置对象
361
+ * @param {object} config - 配置选项
362
+ * @returns {Config} 配置实例
363
+ */
364
+ function getConfig(options, config) {
365
+ if (!config_instance) {
366
+ config_instance = new Config(config, options);
367
+ }
368
+ return config_instance;
369
+ }
370
+
371
+ // 模块导出
372
+ module.exports = {
373
+ Config,
374
+ create,
375
+ createAsync,
376
+ clear,
377
+ clearAll,
378
+ conf,
379
+ getConfig
380
+ };
package/lib/config.js ADDED
@@ -0,0 +1,34 @@
1
+ const KvStore = require('mm_kv_store').KvStore;
2
+
3
+ /**
4
+ * 固定配置存储类,仅允许在系统启动时设置一次,设置后不能修改
5
+ * @class
6
+ * @augments {KvStore}
7
+ */
8
+ class Config extends KvStore {
9
+ /**
10
+ * 获取存储项名称
11
+ * @returns {string} 存储项名称
12
+ */
13
+ _getName() {
14
+ return '配置项';
15
+ }
16
+
17
+ /**
18
+ * 是否允许覆盖已存在的配置项
19
+ * @returns {boolean} 不允许覆盖返回 false
20
+ */
21
+ _isOverwritable() {
22
+ return false;
23
+ }
24
+
25
+ /**
26
+ * 加载时是否覆盖已存在的配置项
27
+ * @returns {boolean} 不覆盖返回 false
28
+ */
29
+ _isLoadOverwritable() {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ module.exports = Config;
@@ -0,0 +1,134 @@
1
+ /**
2
+ * get_run_path - 获取当前程序运行根目录
3
+ *
4
+ * 检测当前运行路径是否为mm_os项目,若是则返回关键路径信息,
5
+ * 方便智能体直接在当前项目下开发插件/应用/API等模块。
6
+ */
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+
10
+ /**
11
+ * 判断指定目录是否为mm_os项目
12
+ */
13
+ function checkIsMmOs(dir_path) {
14
+ // 检测指标1: index.js中存在 MM_os 或 require('mm_os')
15
+ const index_js_path = path.join(dir_path, 'index.js');
16
+ if (fs.existsSync(index_js_path)) {
17
+ try {
18
+ const content = fs.readFileSync(index_js_path, 'utf-8');
19
+ if (content.includes('MM_os') || content.includes("require('mm_os')") || content.includes('require("mm_os")')) {
20
+ return true;
21
+ }
22
+ } catch (e) {
23
+ // 忽略读取错误
24
+ }
25
+ }
26
+
27
+ // 检测指标2: node_modules/mm_os 存在
28
+ const mm_os_module_path = path.join(dir_path, 'node_modules', 'mm_os');
29
+ if (fs.existsSync(mm_os_module_path)) {
30
+ return true;
31
+ }
32
+
33
+ // 检测指标3: app/ 目录 + config/ 目录同时存在(典型mm_os结构)
34
+ const app_path = path.join(dir_path, 'app');
35
+ const config_path = path.join(dir_path, 'config');
36
+ if (fs.existsSync(app_path) && fs.existsSync(config_path)) {
37
+ // 进一步验证:检查app下是否有多个应用模块目录
38
+ try {
39
+ const apps = fs.readdirSync(app_path);
40
+ const has_app_modules = apps.some(name => {
41
+ const app_dir = path.join(app_path, name);
42
+ return fs.statSync(app_dir).isDirectory() &&
43
+ (fs.existsSync(path.join(app_dir, 'app.json')) || fs.existsSync(path.join(app_dir, 'index.js')));
44
+ });
45
+ if (has_app_modules) {
46
+ return true;
47
+ }
48
+ } catch (e) {
49
+ // 忽略
50
+ }
51
+ }
52
+
53
+ return false;
54
+ }
55
+
56
+ /**
57
+ * 获取mm_os版本号
58
+ */
59
+ function getMmOsVersion(dir_path) {
60
+ try {
61
+ const pkg_path = path.join(dir_path, 'node_modules', 'mm_os', 'package.json');
62
+ if (fs.existsSync(pkg_path)) {
63
+ const pkg = JSON.parse(fs.readFileSync(pkg_path, 'utf-8'));
64
+ return pkg.version || '';
65
+ }
66
+ } catch (e) {
67
+ // 忽略
68
+ }
69
+ return '';
70
+ }
71
+
72
+ /**
73
+ * 获取mm_os项目的关键子目录路径
74
+ */
75
+ function getProjectPaths(dir_path) {
76
+ return {
77
+ app: path.join(dir_path, 'app'),
78
+ config: path.join(dir_path, 'config'),
79
+ com: path.join(dir_path, 'com'),
80
+ static: path.join(dir_path, 'static')
81
+ };
82
+ }
83
+
84
+ /**
85
+ * 主函数
86
+ */
87
+ async function main(params, ctx, options) {
88
+ try {
89
+ const check_only = params && params.check_only === true;
90
+ const run_path = process.cwd() + path.sep;
91
+
92
+ // 检测是否为mm_os项目
93
+ const is_mm_os = checkIsMmOs(run_path);
94
+
95
+ let result = {
96
+ run_path: run_path,
97
+ is_mm_os: is_mm_os,
98
+ code: 0,
99
+ msg: is_mm_os ? '当前为mm_os项目' : '当前不是mm_os项目'
100
+ };
101
+
102
+ if (is_mm_os && !check_only) {
103
+ // 获取mm_os版本
104
+ result.mm_os_version = getMmOsVersion(run_path);
105
+
106
+ // 获取关键子目录路径
107
+ const sub_paths = getProjectPaths(run_path);
108
+ result.paths = {};
109
+
110
+ // 只返回实际存在的目录
111
+ for (const [key, dir_path] of Object.entries(sub_paths)) {
112
+ if (fs.existsSync(dir_path)) {
113
+ result.paths[key] = dir_path;
114
+ }
115
+ }
116
+ }
117
+
118
+ return result;
119
+ } catch (error) {
120
+ return {
121
+ run_path: process.cwd(),
122
+ is_mm_os: false,
123
+ code: -1,
124
+ msg: '获取运行路径失败: ' + error.message,
125
+ error: {
126
+ name: error.name,
127
+ message: error.message,
128
+ stack: error.stack
129
+ }
130
+ };
131
+ }
132
+ }
133
+
134
+ exports.main = main;
@@ -0,0 +1,100 @@
1
+ const mm_config = require('mm_config');
2
+
3
+ /**
4
+ * 配置管理器
5
+ * 基于 mm_config 实现文件持久化配置,支持 scope 命名空间
6
+ * @param {object} ctx 上下文对象
7
+ * @param {object} params 步骤参数
8
+ */
9
+ async function main(params, ctx, options) {
10
+ var action = params.action || 'get';
11
+ var key = params.key;
12
+ var value = params.value;
13
+ var scope = params.scope || 'default';
14
+
15
+ var file_path = _getFilePath(params, this);
16
+ // 从磁盘加载已有配置,避免每次 create 新建空配置导致数据丢失
17
+ var loaded = {};
18
+ try {
19
+ loaded = file_path.loadJson() || {};
20
+ } catch (_e) {
21
+ void _e;
22
+ }
23
+ var config = mm_config.create(file_path, loaded);
24
+
25
+ var scope_obj;
26
+ switch (action) {
27
+ case 'get':
28
+ scope_obj = config[scope] || {};
29
+ ctx.output = { obj: scope_obj[key] };
30
+ break;
31
+ case 'list':
32
+ scope_obj = config[scope] || {};
33
+ ctx.output = { list: Object.keys(scope_obj), count: Object.keys(scope_obj).length };
34
+ break;
35
+ case 'values':
36
+ scope_obj = config[scope] || {};
37
+ ctx.output = { list: Object.values(scope_obj), count: Object.keys(scope_obj).length };
38
+ break;
39
+ case 'set':
40
+ scope_obj = config[scope] || {};
41
+ scope_obj[key] = value;
42
+ config[scope] = scope_obj;
43
+ ctx.output = { msg: '配置设置成功' };
44
+ break;
45
+ case 'update':
46
+ scope_obj = config[scope] || {};
47
+ scope_obj[key] = { ...(scope_obj[key] || {}), ...value };
48
+ config[scope] = scope_obj;
49
+ ctx.output = { msg: '配置更新成功' };
50
+ break;
51
+ case 'clear':
52
+ config[scope] = {};
53
+ ctx.output = { msg: '配置清空成功' };
54
+ break;
55
+ case 'del':
56
+ scope_obj = config[scope] || {};
57
+ if (key in scope_obj) {
58
+ delete scope_obj[key];
59
+ config[scope] = scope_obj;
60
+ ctx.output = { msg: '配置删除成功' };
61
+ } else {
62
+ ctx.output = { msg: '配置删除失败' };
63
+ }
64
+ break;
65
+ case 'has':
66
+ scope_obj = config[scope] || {};
67
+ ctx.output = { obj: key in scope_obj };
68
+ break;
69
+ default:
70
+ ctx.output = {
71
+ error: { code: 'MGR_UNKNOWN_ACTION', message: '不支持的操作: ' + action }
72
+ };
73
+ }
74
+
75
+ return ctx.output;
76
+ }
77
+
78
+ /**
79
+ * 获取配置文件路径
80
+ * 优先从 params.file_path 获取,fallback 到模块 options 配置
81
+ * @param {object} params 步骤参数
82
+ * @param {object} ctx_this 模块上下文
83
+ * @returns {string} 配置文件路径
84
+ */
85
+ function _getFilePath(params, ctx_this) {
86
+ var opts = (ctx_this && ctx_this.config && ctx_this.config.options) || {};
87
+ var default_path = './config';
88
+ if (
89
+ opts.file_path &&
90
+ typeof opts.file_path === 'object' &&
91
+ opts.file_path.default !== undefined
92
+ ) {
93
+ default_path = opts.file_path.default;
94
+ } else if (opts.file_path) {
95
+ default_path = opts.file_path;
96
+ }
97
+ return params.file_path || default_path;
98
+ }
99
+
100
+ module.exports = { main };
@@ -0,0 +1,7 @@
1
+ 'use strict';
2
+ /**
3
+ * get_run_path —— 工具契约适配层
4
+ * 业务实现归位于模块 lib/run_path_logic.js,本文件只把模块能力暴露给工具加载器。
5
+ * 其它模块可直接 require('mm_config').runPathLogic 复用,无需经过工具注册面。
6
+ */
7
+ module.exports = require('../../run_path_logic.js');
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ /** 模块能力层:懒加载工具实现,避免模块入口被 require 时加载全部实现 */
5
+ module.exports = new Proxy({}, {
6
+ get(_t, key) {
7
+ if (typeof key !== 'string') return undefined;
8
+ if (!fs.existsSync(path.join(__dirname, key, 'index.js'))) return undefined;
9
+ return require('./' + key);
10
+ },
11
+ has(_t, key) {
12
+ return typeof key === 'string' && fs.existsSync(path.join(__dirname, key, 'index.js'));
13
+ },
14
+ ownKeys() { return fs.readdirSync(__dirname, { withFileTypes: true }).filter(e => e.isDirectory()).map(e => e.name); },
15
+ getOwnPropertyDescriptor(_t, key) { return this.has(_t, key) ? { enumerable: true, configurable: true } : undefined; }
16
+ });