@aiot-toolkit/shared-utils 2.0.3-beta.6 → 2.0.3-beta.8

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,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;
@@ -1,143 +1,146 @@
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 ansi_colors_1 = __importDefault(require("ansi-colors"));
16
- const cli_progress_1 = __importDefault(require("cli-progress"));
17
- const koa_1 = __importDefault(require("koa"));
18
- const koa_router_1 = __importDefault(require("koa-router"));
19
- const koa_static_1 = __importDefault(require("koa-static"));
20
- const os_1 = __importDefault(require("os"));
21
- const portfinder_1 = __importDefault(require("portfinder"));
22
- const simple_git_1 = __importDefault(require("simple-git"));
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.default = void 0;
7
+ var _ansiColors = _interopRequireDefault(require("ansi-colors"));
8
+ var _cliProgress = _interopRequireDefault(require("cli-progress"));
9
+ var _koa = _interopRequireDefault(require("koa"));
10
+ var _koaRouter = _interopRequireDefault(require("koa-router"));
11
+ var _koaStatic = _interopRequireDefault(require("koa-static"));
12
+ var _os = _interopRequireDefault(require("os"));
13
+ var _portfinder = _interopRequireDefault(require("portfinder"));
14
+ var _simpleGit = _interopRequireDefault(require("simple-git"));
15
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
23
16
  /**
24
17
  * NetworkUtil
25
18
  */
26
19
  class NetworkUtil {
27
- /**
28
- * clone git 项目
29
- * @param url
30
- * @param localPath
31
- * @param showProgress 是否显示进度条,默认为 true,会在命令行工具中显示绿色进度条
32
- * @returns
33
- */
34
- static gitClone(url, localPath, showProgress = true) {
35
- return new Promise((resolve, reject) => {
36
- let bar;
37
- if (showProgress) {
38
- bar = new cli_progress_1.default.SingleBar({
39
- format: `progress: {percentage}% ${ansi_colors_1.default.green(`{bar}`)} {value}/{total}`
40
- }, cli_progress_1.default.Presets.shades_classic);
41
- bar.start(100, 0);
42
- }
43
- (0, simple_git_1.default)({
44
- progress: (data) => {
45
- if (bar) {
46
- bar.setTotal(data.total);
47
- bar.update(data.processed);
48
- }
49
- }
50
- })
51
- .clone(url, localPath)
52
- .then(() => {
53
- resolve();
54
- })
55
- .catch((error) => {
56
- reject(error);
57
- })
58
- .finally(() => {
59
- if (bar) {
60
- bar.stop();
61
- }
62
- });
63
- });
64
- }
65
- /**
66
- * 创建 http 服务器
67
- * @param data
68
- * @returns
69
- */
70
- static createHttpServer(data) {
71
- return __awaiter(this, void 0, void 0, function* () {
72
- const { wantPort, routeConfigList, events, staticFolder } = data;
73
- const app = new koa_1.default();
74
- const port = yield portfinder_1.default.getPortPromise({
75
- port: wantPort
76
- });
77
- if (staticFolder) {
78
- app.use((0, koa_static_1.default)(staticFolder));
79
- }
80
- const router = new koa_router_1.default();
81
- for (const config of routeConfigList) {
82
- const { routeList } = config;
83
- for (const route of routeList) {
84
- const { path, method = 'get', handler } = route;
85
- router[method](path, handler);
86
- }
87
- }
88
- app.use(router.routes());
89
- const server = app.listen(port, () => {
90
- var _a;
91
- (_a = events === null || events === void 0 ? void 0 : events.onSuccess) === null || _a === void 0 ? void 0 : _a.call(events, port);
92
- });
93
- return { server, port, app };
94
- });
95
- }
96
- static getIPv4IPAddress() {
97
- const ifaces = os_1.default.networkInterfaces();
98
- if (!ifaces) {
99
- return;
20
+ /**
21
+ * clone git 项目
22
+ * @param url
23
+ * @param localPath
24
+ * @param showProgress 是否显示进度条,默认为 true,会在命令行工具中显示绿色进度条
25
+ * @returns
26
+ */
27
+ static gitClone(url, localPath) {
28
+ let showProgress = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
29
+ return new Promise((resolve, reject) => {
30
+ let bar;
31
+ if (showProgress) {
32
+ bar = new _cliProgress.default.SingleBar({
33
+ format: `progress: {percentage}% ${_ansiColors.default.green(`{bar}`)} {value}/{total}`
34
+ }, _cliProgress.default.Presets.shades_classic);
35
+ bar.start(100, 0);
36
+ }
37
+ (0, _simpleGit.default)({
38
+ progress: data => {
39
+ if (bar) {
40
+ bar.setTotal(data.total);
41
+ bar.update(data.processed);
42
+ }
100
43
  }
101
- for (const prop in ifaces) {
102
- const iface = ifaces[prop];
103
- if (iface) {
104
- for (let item of iface) {
105
- if (item.family === 'IPv4' && !item.internal && item.address !== '127.0.0.1') {
106
- return item.address;
107
- }
108
- }
109
- }
44
+ }).clone(url, localPath).then(() => {
45
+ resolve();
46
+ }).catch(error => {
47
+ reject(error);
48
+ }).finally(() => {
49
+ if (bar) {
50
+ bar.stop();
110
51
  }
52
+ });
53
+ });
54
+ }
55
+
56
+ /**
57
+ * 创建 http 服务器
58
+ * @param data
59
+ * @returns
60
+ */
61
+ static async createHttpServer(data) {
62
+ const {
63
+ wantPort,
64
+ routeConfigList,
65
+ events,
66
+ staticFolder
67
+ } = data;
68
+ const app = new _koa.default();
69
+ const port = await _portfinder.default.getPortPromise({
70
+ port: wantPort
71
+ });
72
+ if (staticFolder) {
73
+ app.use((0, _koaStatic.default)(staticFolder));
111
74
  }
112
- /**
113
- * 从请求中获取客户端 ip
114
- * @param ctx koa的请求上下文
115
- * @returns
116
- */
117
- static getClientIp(ctx) {
118
- const request = ctx.request;
119
- const ip = request.headers['x-forwarded-for'] ||
120
- request.header['x-real-ip'] ||
121
- request.socket.remoteAddress;
122
- if (ip) {
123
- return NetworkUtil.stripPrefixForIPV4MappedIPV6Address(ip.toString());
124
- }
75
+ const router = new _koaRouter.default();
76
+ for (const config of routeConfigList) {
77
+ const {
78
+ routeList
79
+ } = config;
80
+ for (const route of routeList) {
81
+ const {
82
+ path,
83
+ method = 'get',
84
+ handler
85
+ } = route;
86
+ router[method](path, handler);
87
+ }
125
88
  }
126
- /**
127
- * 从网络地址中获取真实 ip
128
- *
129
- * @example
130
- * @param ip
131
- * @returns
132
- */
133
- static stripPrefixForIPV4MappedIPV6Address(ip) {
134
- if (/^::1$/.test(ip)) {
135
- ip = '127.0.0.1';
136
- }
137
- if (/^::.{0,4}:(\d{1,3}\.){3}\d{1,3}/.test(ip)) {
138
- ip = ip.replace(/^.*:/, '');
89
+ app.use(router.routes());
90
+ const server = app.listen(port, () => {
91
+ events?.onSuccess?.(port);
92
+ });
93
+ return {
94
+ server,
95
+ port,
96
+ app
97
+ };
98
+ }
99
+ static getIPv4IPAddress() {
100
+ const ifaces = _os.default.networkInterfaces();
101
+ if (!ifaces) {
102
+ return;
103
+ }
104
+ for (const prop in ifaces) {
105
+ const iface = ifaces[prop];
106
+ if (iface) {
107
+ for (let item of iface) {
108
+ if (item.family === 'IPv4' && !item.internal && item.address !== '127.0.0.1') {
109
+ return item.address;
110
+ }
139
111
  }
140
- return ip;
112
+ }
113
+ }
114
+ }
115
+
116
+ /**
117
+ * 从请求中获取客户端 ip
118
+ * @param ctx koa的请求上下文
119
+ * @returns
120
+ */
121
+ static getClientIp(ctx) {
122
+ const request = ctx.request;
123
+ const ip = request.headers['x-forwarded-for'] || request.header['x-real-ip'] || request.socket.remoteAddress;
124
+ if (ip) {
125
+ return NetworkUtil.stripPrefixForIPV4MappedIPV6Address(ip.toString());
126
+ }
127
+ }
128
+
129
+ /**
130
+ * 从网络地址中获取真实 ip
131
+ *
132
+ * @example
133
+ * @param ip
134
+ * @returns
135
+ */
136
+ static stripPrefixForIPV4MappedIPV6Address(ip) {
137
+ if (/^::1$/.test(ip)) {
138
+ ip = '127.0.0.1';
139
+ }
140
+ if (/^::.{0,4}:(\d{1,3}\.){3}\d{1,3}/.test(ip)) {
141
+ ip = ip.replace(/^.*:/, '');
141
142
  }
143
+ return ip;
144
+ }
142
145
  }
143
- exports.default = NetworkUtil;
146
+ var _default = exports.default = NetworkUtil;