@aiot-toolkit/shared-utils 2.0.3-beta.1 → 2.0.3-beta.10

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.
@@ -1,13 +1,19 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
3
6
  exports.Loglevel = void 0;
4
7
  // 日志类别
5
- var Loglevel;
6
- (function (Loglevel) {
7
- Loglevel[Loglevel["LOG"] = 0] = "LOG";
8
- Loglevel[Loglevel["SUCCESS"] = 1] = "SUCCESS";
9
- Loglevel[Loglevel["INFO"] = 2] = "INFO";
10
- Loglevel[Loglevel["WARN"] = 3] = "WARN";
11
- Loglevel[Loglevel["ERROR"] = 4] = "ERROR";
12
- Loglevel[Loglevel["THROW"] = 5] = "THROW";
13
- })(Loglevel || (exports.Loglevel = Loglevel = {}));
8
+ let Loglevel = exports.Loglevel = /*#__PURE__*/function (Loglevel) {
9
+ Loglevel[Loglevel["LOG"] = 0] = "LOG";
10
+ Loglevel[Loglevel["SUCCESS"] = 1] = "SUCCESS";
11
+ Loglevel[Loglevel["INFO"] = 2] = "INFO";
12
+ Loglevel[Loglevel["WARN"] = 3] = "WARN";
13
+ Loglevel[Loglevel["ERROR"] = 4] = "ERROR";
14
+ Loglevel[Loglevel["THROW"] = 5] = "THROW";
15
+ return Loglevel;
16
+ }({});
17
+ /**
18
+ * ILog
19
+ */
@@ -1,2 +1,5 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
@@ -1,2 +1,5 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
package/lib/type/Type.js CHANGED
@@ -1,2 +1,5 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
@@ -1,116 +1,125 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const crypto_1 = __importDefault(require("crypto"));
7
- const ajv_1 = __importDefault(require("ajv"));
8
- const fs_1 = __importDefault(require("fs"));
9
- const path_1 = __importDefault(require("path"));
10
- const qrcode_1 = __importDefault(require("qrcode"));
11
- const ColorConsole_1 = __importDefault(require("../ColorConsole"));
12
- const ILog_1 = require("../interface/ILog");
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _crypto = _interopRequireDefault(require("crypto"));
8
+ var _ajv = _interopRequireDefault(require("ajv"));
9
+ var _fs = _interopRequireDefault(require("fs"));
10
+ var _path = _interopRequireDefault(require("path"));
11
+ var _qrcode = _interopRequireDefault(require("qrcode"));
12
+ var _ColorConsole = _interopRequireDefault(require("../ColorConsole"));
13
+ var _ILog = require("../interface/ILog");
14
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
13
15
  /**
14
16
  * 不好分类的工具函数
15
17
  */
16
18
  class CommonUtil {
17
- /**
18
- * 根据 buffer 生成 hash 值
19
- *
20
- * 用于唯一标识流内容,通常用于文件校验
21
- * @param buffer
22
- * @returns hash 值
23
- */
24
- static calcDataDigest(buffer) {
25
- const hash = crypto_1.default.createHash('SHA256');
26
- hash.update(buffer);
27
- return hash.digest();
19
+ /**
20
+ * 根据 buffer 生成 hash 值
21
+ *
22
+ * 用于唯一标识流内容,通常用于文件校验
23
+ * @param buffer
24
+ * @returns hash 值
25
+ */
26
+ static calcDataDigest(buffer) {
27
+ const hash = _crypto.default.createHash('SHA256');
28
+ hash.update(buffer);
29
+ return hash.digest();
30
+ }
31
+ static calcImageDigest(filePath) {
32
+ const data = _fs.default.readFileSync(filePath);
33
+ const hash = _crypto.default.createHash('md5').update(data);
34
+ return hash.digest('hex').substring(0, 8);
35
+ }
36
+
37
+ /**
38
+ * 从开发者项目的 node_module 中加载指定依赖;
39
+ * 如果不存在,提示下载;存在则返回加载的依赖
40
+ * @param packageName
41
+ */
42
+ static requireNodeModule(projectPath, packageName) {
43
+ const modulePath = _path.default.resolve(projectPath, `./node_modules/${packageName}`);
44
+ if (!_fs.default.existsSync(modulePath)) {
45
+ return Promise.reject(new Error(_ColorConsole.default.createMessage([{
46
+ word: packageName,
47
+ style: _ColorConsole.default.getStyle(_ILog.Loglevel.ERROR)
48
+ }, 'is missing, run', {
49
+ word: `npm i ${packageName}`,
50
+ style: _ColorConsole.default.getStyle(_ILog.Loglevel.ERROR)
51
+ }, 'to install it'])));
28
52
  }
29
- static calcImageDigest(filePath) {
30
- const data = fs_1.default.readFileSync(filePath);
31
- const hash = crypto_1.default.createHash('md5').update(data);
32
- return hash.digest('hex').substring(0, 8);
53
+ return Promise.resolve(require(modulePath));
54
+ }
55
+ static requireModule(path) {
56
+ let throwError = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
57
+ if (!_fs.default.existsSync(path)) {
58
+ if (throwError) {
59
+ throw new Error(`${path} is missing`);
60
+ }
61
+ return;
33
62
  }
34
- /**
35
- * 从开发者项目的 node_module 中加载指定依赖;
36
- * 如果不存在,提示下载;存在则返回加载的依赖
37
- * @param packageName
38
- */
39
- static requireNodeModule(projectPath, packageName) {
40
- const modulePath = path_1.default.resolve(projectPath, `./node_modules/${packageName}`);
41
- if (!fs_1.default.existsSync(modulePath)) {
42
- return Promise.reject(new Error(ColorConsole_1.default.createMessage([
43
- {
44
- word: packageName,
45
- style: ColorConsole_1.default.getStyle(ILog_1.Loglevel.ERROR)
46
- },
47
- 'is missing, run',
48
- {
49
- word: `npm i ${packageName}`,
50
- style: ColorConsole_1.default.getStyle(ILog_1.Loglevel.ERROR)
51
- },
52
- 'to install it'
53
- ])));
54
- }
55
- return Promise.resolve(require(modulePath));
63
+ try {
64
+ return require(path);
65
+ } catch (error) {
66
+ if (throwError) {
67
+ throw error;
68
+ }
69
+ return;
56
70
  }
57
- static requireModule(path, throwError = false) {
58
- if (!fs_1.default.existsSync(path)) {
59
- if (throwError) {
60
- throw new Error(`${path} is missing`);
61
- }
62
- return;
63
- }
64
- try {
65
- return require(path);
66
- }
67
- catch (error) {
68
- if (throwError) {
69
- throw error;
70
- }
71
- return;
72
- }
71
+ }
72
+
73
+ /**
74
+ * 验证 json 内容
75
+ * @param json json 内容
76
+ * @param schema 验证配置, 详见:https://github.com/ajv-validator/ajv
77
+ *
78
+ *
79
+ * @example
80
+ * ```
81
+ * CommonUtil.validateJson({a:123},
82
+ * {
83
+ * a:{
84
+ * type:'number'
85
+ * }
86
+ * }
87
+ * )
88
+ * ```
89
+ * @returns
90
+ */
91
+ static validateJson(json, schema) {
92
+ if (!json || !schema) {
93
+ return;
73
94
  }
74
- /**
75
- * 验证 json 内容
76
- * @param json json 内容
77
- * @param schema 验证配置, 详见:https://github.com/ajv-validator/ajv
78
- *
79
- *
80
- * @example
81
- * ```
82
- * CommonUtil.validateJson({a:123},
83
- * {
84
- * a:{
85
- * type:'number'
86
- * }
87
- * }
88
- * )
89
- * ```
90
- * @returns
91
- */
92
- static validateJson(json, schema) {
93
- if (!json || !schema) {
94
- return;
95
- }
96
- const ajv = new ajv_1.default({ allErrors: true, allowUnionTypes: true });
97
- ajv.validate(schema, json);
98
- if (ajv.errors) {
99
- const errors = ajv.errors.map((item) => {
100
- const { message, instancePath, keyword } = item;
101
- const errorMessage = `${instancePath ? `${instancePath}: ` : ''}${message}`;
102
- if (keyword === 'required') {
103
- return new TypeError(errorMessage);
104
- }
105
- return new Error(errorMessage);
106
- });
107
- return errors;
95
+ const ajv = new _ajv.default({
96
+ allErrors: true,
97
+ allowUnionTypes: true
98
+ });
99
+ ajv.validate(schema, json);
100
+ if (ajv.errors) {
101
+ const errors = ajv.errors.map(item => {
102
+ const {
103
+ message,
104
+ instancePath,
105
+ keyword
106
+ } = item;
107
+ const errorMessage = `${instancePath ? `${instancePath}: ` : ''}${message}`;
108
+ if (keyword === 'required') {
109
+ return new TypeError(errorMessage);
108
110
  }
111
+ return new Error(errorMessage);
112
+ });
113
+ return errors;
109
114
  }
110
- static outputQRCodeOnTerminal(text) {
111
- return qrcode_1.default.toString(text, { type: 'utf8', margin: 0 }).then((qrcode) => {
112
- console.log(qrcode);
113
- });
114
- }
115
+ }
116
+ static outputQRCodeOnTerminal(text) {
117
+ return _qrcode.default.toString(text, {
118
+ type: 'utf8',
119
+ margin: 0
120
+ }).then(qrcode => {
121
+ console.log(qrcode);
122
+ });
123
+ }
115
124
  }
116
- exports.default = CommonUtil;
125
+ var _default = exports.default = CommonUtil;
@@ -1,178 +1,183 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const fs_extra_1 = __importDefault(require("fs-extra"));
16
- const path_1 = __importDefault(require("path"));
17
- const rimraf_1 = require("rimraf");
18
- const fswin_1 = __importDefault(require("fswin"));
19
- const minimatch_1 = require("minimatch");
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _fsExtra = _interopRequireDefault(require("fs-extra"));
8
+ var _path = _interopRequireDefault(require("path"));
9
+ var _rimraf = require("rimraf");
10
+ var _fswin = _interopRequireDefault(require("fswin"));
11
+ var _minimatch = require("minimatch");
12
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
20
13
  /**
21
14
  * FileUtil
22
15
  */
23
16
  class FileUtil {
24
- /**
25
- * 判断字符串是否符合包含、不包含的条件
26
- *
27
- * 规则为:
28
- * 1. 如果设置了不包含且匹配,则不包含
29
- * 2. 否则,如果设置了包含且不匹配,则不包含
30
- * 3. 否则,包含
31
- * @param value
32
- * @param include
33
- * @param exclude
34
- */
35
- static include(path, include, exclude) {
36
- if (exclude && this.match(path, exclude)) {
37
- return false;
38
- }
39
- if (include && !this.match(path, include)) {
40
- return false;
41
- }
42
- return true;
17
+ /**
18
+ * 判断字符串是否符合包含、不包含的条件
19
+ *
20
+ * 规则为:
21
+ * 1. 如果设置了不包含且匹配,则不包含
22
+ * 2. 否则,如果设置了包含且不匹配,则不包含
23
+ * 3. 否则,包含
24
+ * @param value
25
+ * @param include
26
+ * @param exclude
27
+ */
28
+ static include(path, include, exclude) {
29
+ if (exclude && this.match(path, exclude)) {
30
+ return false;
43
31
  }
44
- /**
45
- * 判断字符串是否匹配指定规则
46
- * @param value
47
- * @param matchType
48
- * @returns
49
- */
50
- static match(value, matchType) {
51
- switch (typeof matchType) {
52
- case 'function':
53
- return matchType(value);
54
- case 'string':
55
- return (0, minimatch_1.minimatch)(value, matchType, { dot: true });
56
- case 'object':
57
- if (matchType instanceof RegExp) {
58
- return matchType.test(value);
59
- }
60
- else if (matchType instanceof Array) {
61
- // 递归检查每一项
62
- let result = matchType.find((item) => this.match(value, item));
63
- if (result) {
64
- return true;
65
- }
66
- }
67
- return false;
68
- default:
69
- return false;
70
- }
32
+ if (include && !this.match(path, include)) {
33
+ return false;
71
34
  }
72
- /**
73
- * 获取指定目录所有层级的文件
74
- * @param dir
75
- * @returns
76
- */
77
- static readAlldirSync(dir, includes, excludes) {
78
- const files = fs_extra_1.default.readdirSync(dir, { withFileTypes: true });
79
- const result = [];
80
- files.forEach((item) => {
81
- const itemPath = path_1.default.join(dir, item.name);
82
- if (item.isDirectory()) {
83
- // 当目录不被排除时,递归获取子目录
84
- if (this.include(itemPath, undefined, excludes)) {
85
- const children = this.readAlldirSync(itemPath, includes, excludes);
86
- result.push(...children);
87
- }
88
- }
89
- else {
90
- if (this.include(itemPath, includes, excludes)) {
91
- result.push(itemPath);
92
- }
93
- }
35
+ return true;
36
+ }
37
+ /**
38
+ * 判断字符串是否匹配指定规则
39
+ * @param value
40
+ * @param matchType
41
+ * @returns
42
+ */
43
+ static match(value, matchType) {
44
+ switch (typeof matchType) {
45
+ case 'function':
46
+ return matchType(value);
47
+ case 'string':
48
+ return (0, _minimatch.minimatch)(value, matchType, {
49
+ dot: true
94
50
  });
95
- return result;
96
- }
97
- /**
98
- * 替换文件内容
99
- *
100
- * @see replaceKeywords
101
- * @param filePath
102
- * @param keywordDic
103
- */
104
- static replaceFileContent(filePath, keywordDic) {
105
- let content = fs_extra_1.default.readFileSync(filePath, 'utf-8');
106
- content = this.replaceKeywords(content, keywordDic);
107
- fs_extra_1.default.writeFileSync(filePath, content);
108
- }
109
- /**
110
- * 替换字符串内容
111
- *
112
- * @example
113
- * // 替换 abc{{value}} 为 abc123
114
- * replaceKeywords(`abc{{value}}`, {value: '123'})
115
- *
116
- * @param content
117
- * @param keywordDic
118
- * @returns
119
- */
120
- static replaceKeywords(content, keywordDic) {
121
- return content.replace(/{{(.*?)}}/gm, (origin, key) => {
122
- key = key.trim();
123
- return keywordDic[key] !== undefined ? keywordDic[key] : origin;
124
- });
125
- }
126
- /**
127
- * 更新文件路径
128
- * @param filePath
129
- * @param newFileName
130
- * @returns
131
- * @example updateFileName('./a/b/c.ux', 'd.js') 转换结果为'./a/b/d.js'
132
- */
133
- static updateFileName(filePath, newFileName) {
134
- return filePath && newFileName ? path_1.default.join(path_1.default.dirname(filePath), newFileName) : '';
135
- }
136
- /**
137
- * 复制文件
138
- * @param sourceDir 源目录
139
- * @param targetDir 目标目录
140
- * @param excludes 不包含的文件
141
- * @param includes 包含的文件
142
- */
143
- static copyFiles(sourceDir, targetDir, excludes, includes) {
144
- const files = FileUtil.readAlldirSync(sourceDir, includes, excludes);
145
- for (let file of files) {
146
- const targetPath = path_1.default.join(targetDir, path_1.default.relative(sourceDir, file));
147
- fs_extra_1.default.copySync(file, targetPath, { overwrite: true });
51
+ case 'object':
52
+ if (matchType instanceof RegExp) {
53
+ return matchType.test(value);
54
+ } else if (matchType instanceof Array) {
55
+ // 递归检查每一项
56
+ let result = matchType.find(item => this.match(value, item));
57
+ if (result) {
58
+ return true;
59
+ }
148
60
  }
61
+ return false;
62
+ default:
63
+ return false;
149
64
  }
150
- /**
151
- * 检查指定的文件列表是否全部存在
152
- * @param fileList 文件列表
153
- */
154
- static checkFilePath(fileList) {
155
- return fileList === null || fileList === void 0 ? void 0 : fileList.every((filePath) => fs_extra_1.default.existsSync(filePath));
156
- }
157
- static del(patterns, options) {
158
- return __awaiter(this, void 0, void 0, function* () {
159
- return (0, rimraf_1.rimrafSync)(patterns, Object.assign({ glob: true }, options));
160
- });
161
- }
162
- /**
163
- * 创建目录
164
- *
165
- * *支持 windows 系统创建隐藏目录
166
- * @param path
167
- * @param options
168
- * @returns
169
- */
170
- static mkdirSync(path, options) {
171
- const result = fs_extra_1.default.mkdirSync(path, options);
172
- if (fswin_1.default && (options === null || options === void 0 ? void 0 : options.hidden)) {
173
- fswin_1.default.setAttributesSync(path.toString(), { IS_HIDDEN: true });
65
+ }
66
+ /**
67
+ * 获取指定目录所有层级的文件
68
+ * @param dir
69
+ * @returns
70
+ */
71
+
72
+ static readAlldirSync(dir, includes, excludes) {
73
+ const files = _fsExtra.default.readdirSync(dir, {
74
+ withFileTypes: true
75
+ });
76
+ const result = [];
77
+ files.forEach(item => {
78
+ const itemPath = _path.default.join(dir, item.name);
79
+ if (item.isDirectory()) {
80
+ // 当目录不被排除时,递归获取子目录
81
+ if (this.include(itemPath, undefined, excludes)) {
82
+ const children = this.readAlldirSync(itemPath, includes, excludes);
83
+ result.push(...children);
84
+ }
85
+ } else {
86
+ if (this.include(itemPath, includes, excludes)) {
87
+ result.push(itemPath);
174
88
  }
175
- return result;
89
+ }
90
+ });
91
+ return result;
92
+ }
93
+
94
+ /**
95
+ * 替换文件内容
96
+ *
97
+ * @see replaceKeywords
98
+ * @param filePath
99
+ * @param keywordDic
100
+ */
101
+ static replaceFileContent(filePath, keywordDic) {
102
+ let content = _fsExtra.default.readFileSync(filePath, 'utf-8');
103
+ content = this.replaceKeywords(content, keywordDic);
104
+ _fsExtra.default.writeFileSync(filePath, content);
105
+ }
106
+
107
+ /**
108
+ * 替换字符串内容
109
+ *
110
+ * @example
111
+ * // 替换 abc{{value}} 为 abc123
112
+ * replaceKeywords(`abc{{value}}`, {value: '123'})
113
+ *
114
+ * @param content
115
+ * @param keywordDic
116
+ * @returns
117
+ */
118
+ static replaceKeywords(content, keywordDic) {
119
+ return content.replace(/{{(.*?)}}/gm, (origin, key) => {
120
+ key = key.trim();
121
+ return keywordDic[key] !== undefined ? keywordDic[key] : origin;
122
+ });
123
+ }
124
+ /**
125
+ * 更新文件路径
126
+ * @param filePath
127
+ * @param newFileName
128
+ * @returns
129
+ * @example updateFileName('./a/b/c.ux', 'd.js') 转换结果为'./a/b/d.js'
130
+ */
131
+ static updateFileName(filePath, newFileName) {
132
+ return filePath && newFileName ? _path.default.join(_path.default.dirname(filePath), newFileName) : '';
133
+ }
134
+
135
+ /**
136
+ * 复制文件
137
+ * @param sourceDir 源目录
138
+ * @param targetDir 目标目录
139
+ * @param excludes 不包含的文件
140
+ * @param includes 包含的文件
141
+ */
142
+ static copyFiles(sourceDir, targetDir, excludes, includes) {
143
+ const files = FileUtil.readAlldirSync(sourceDir, includes, excludes);
144
+ for (let file of files) {
145
+ const targetPath = _path.default.join(targetDir, _path.default.relative(sourceDir, file));
146
+ _fsExtra.default.copySync(file, targetPath, {
147
+ overwrite: true
148
+ });
149
+ }
150
+ }
151
+ /**
152
+ * 检查指定的文件列表是否全部存在
153
+ * @param fileList 文件列表
154
+ */
155
+ static checkFilePath(fileList) {
156
+ return fileList?.every(filePath => _fsExtra.default.existsSync(filePath));
157
+ }
158
+ static async del(patterns, options) {
159
+ return (0, _rimraf.rimrafSync)(patterns, {
160
+ glob: true,
161
+ ...options
162
+ });
163
+ }
164
+
165
+ /**
166
+ * 创建目录
167
+ *
168
+ * *支持 windows 系统创建隐藏目录
169
+ * @param path
170
+ * @param options
171
+ * @returns
172
+ */
173
+ static mkdirSync(path, options) {
174
+ const result = _fsExtra.default.mkdirSync(path, options);
175
+ if (_fswin.default && options?.hidden) {
176
+ _fswin.default.setAttributesSync(path.toString(), {
177
+ IS_HIDDEN: true
178
+ });
176
179
  }
180
+ return result;
181
+ }
177
182
  }
178
- exports.default = FileUtil;
183
+ var _default = exports.default = FileUtil;