@aiot-toolkit/shared-utils 2.0.2-dev.7 → 2.0.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.
@@ -1,5 +1,5 @@
1
- import { ILog, LOG_LEVEL } from './interface/ILog';
2
- interface IStyle {
1
+ import { ILog, Loglevel } from './interface/ILog';
2
+ export interface IStyle {
3
3
  color?: string;
4
4
  bgColor?: string;
5
5
  bold?: boolean;
@@ -16,9 +16,9 @@ export type StyleMessage = string | number | boolean | undefined | {
16
16
  declare class ColorConsole {
17
17
  static defaultStyle: IStyle;
18
18
  static styleDic: {
19
- [key in LOG_LEVEL]: IStyle;
19
+ [key in Loglevel]: IStyle;
20
20
  };
21
- static getStyle(logLevel: LOG_LEVEL): IStyle;
21
+ static getStyle(logLevel: Loglevel): IStyle;
22
22
  static log(...message: StyleMessage[]): void;
23
23
  static error(...message: StyleMessage[]): void;
24
24
  static info(...message: StyleMessage[]): void;
@@ -15,22 +15,22 @@ class ColorConsole {
15
15
  return this.styleDic[logLevel] || this.defaultStyle;
16
16
  }
17
17
  static log(...message) {
18
- return this._log(ILog_1.LOG_LEVEL.Log, ...message);
18
+ return this._log(ILog_1.Loglevel.LOG, ...message);
19
19
  }
20
20
  static error(...message) {
21
- return this._log(ILog_1.LOG_LEVEL.Error, ...message);
21
+ return this._log(ILog_1.Loglevel.ERROR, ...message);
22
22
  }
23
23
  static info(...message) {
24
- return this._log(ILog_1.LOG_LEVEL.Info, ...message);
24
+ return this._log(ILog_1.Loglevel.INFO, ...message);
25
25
  }
26
26
  static success(...message) {
27
- return this._log(ILog_1.LOG_LEVEL.Success, ...message);
27
+ return this._log(ILog_1.Loglevel.SUCCESS, ...message);
28
28
  }
29
29
  static throw(...message) {
30
- this._log(ILog_1.LOG_LEVEL.Throw, ...message);
30
+ this._log(ILog_1.Loglevel.THROW, ...message);
31
31
  }
32
32
  static warn(...message) {
33
- return this._log(ILog_1.LOG_LEVEL.Warn, ...message);
33
+ return this._log(ILog_1.Loglevel.WARN, ...message);
34
34
  }
35
35
  /**
36
36
  * 创建复杂格式的消息,可单独设置词语样式
@@ -55,7 +55,7 @@ class ColorConsole {
55
55
  }
56
56
  static _log(logLevel, ...message) {
57
57
  const style = this.styleDic[logLevel] || this.defaultStyle;
58
- const time = this.formatWord(`[${(0, dayjs_1.default)().format('YYYY-MM-DD HH:mm:ss')}]:`, style);
58
+ const time = this.formatWord(`[${(0, dayjs_1.default)().format('MM-DD HH:mm:ss')}] [toolkit]:`, style);
59
59
  const icon = style.icon ? style.icon : '';
60
60
  console.log(icon, time, this.createMessage(message.map((item) => {
61
61
  if (typeof item === 'object') {
@@ -90,10 +90,10 @@ class ColorConsole {
90
90
  * @returns 返回打印的日志信息
91
91
  */
92
92
  static logger(log) {
93
- const { message, position, filePath, level = ILog_1.LOG_LEVEL.Info } = log;
93
+ const { message, position, filePath, level = ILog_1.Loglevel.INFO } = log;
94
94
  let positionMessage;
95
95
  positionMessage = {
96
- style: this.getStyle(ILog_1.LOG_LEVEL.Info),
96
+ style: this.getStyle(ILog_1.Loglevel.INFO),
97
97
  word: [filePath, position === null || position === void 0 ? void 0 : position.startLine, position === null || position === void 0 ? void 0 : position.startColumn]
98
98
  .filter((item) => Boolean(item))
99
99
  .join(':')
@@ -110,27 +110,27 @@ ColorConsole.defaultStyle = {
110
110
  color: '#cccccc'
111
111
  };
112
112
  ColorConsole.styleDic = {
113
- [ILog_1.LOG_LEVEL.Success]: {
113
+ [ILog_1.Loglevel.SUCCESS]: {
114
114
  color: '#008000',
115
115
  icon: '✅'
116
116
  },
117
- [ILog_1.LOG_LEVEL.Info]: {
117
+ [ILog_1.Loglevel.INFO]: {
118
118
  color: '#03A9F4',
119
119
  icon: 'ℹ️ '
120
120
  },
121
- [ILog_1.LOG_LEVEL.Warn]: {
121
+ [ILog_1.Loglevel.WARN]: {
122
122
  color: '#FF9800',
123
123
  icon: '🟠'
124
124
  },
125
- [ILog_1.LOG_LEVEL.Error]: {
125
+ [ILog_1.Loglevel.ERROR]: {
126
126
  color: '#ff0000',
127
127
  icon: '❌'
128
128
  },
129
- [ILog_1.LOG_LEVEL.Throw]: {
129
+ [ILog_1.Loglevel.THROW]: {
130
130
  color: '#ff0000',
131
131
  bold: true,
132
132
  icon: '❌'
133
133
  },
134
- [ILog_1.LOG_LEVEL.Log]: _a.defaultStyle
134
+ [ILog_1.Loglevel.LOG]: _a.defaultStyle
135
135
  };
136
136
  exports.default = ColorConsole;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * 项目类型
3
+ */
4
+ declare enum ProjectType {
5
+ VELA_UX = "velaUx",
6
+ ANDDROID_UX = "androidUx",
7
+ VELA_XTS = "velaXts"
8
+ }
9
+ declare namespace ProjectType {
10
+ /**
11
+ * 获取项目类型
12
+ *
13
+ * 1. 存在`app/app.xts`:velaXts项目
14
+ * 2. 存在`src/app.ux`
15
+ * 1. `src/manifest.json`文件的 `deviceTypeList` 字段包含`watch`:velaUx
16
+ * 2. 否则:androidUx
17
+ * 3. 否则:velaUx
18
+ * @param projectPath
19
+ * @returns
20
+ */
21
+ function getProjectType(projectPath: string, src?: string): ProjectType;
22
+ }
23
+ export default ProjectType;
@@ -0,0 +1,45 @@
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 path_1 = __importDefault(require("path"));
7
+ const fs_extra_1 = __importDefault(require("fs-extra"));
8
+ /**
9
+ * 项目类型
10
+ */
11
+ var ProjectType;
12
+ (function (ProjectType) {
13
+ ProjectType["VELA_UX"] = "velaUx";
14
+ ProjectType["ANDDROID_UX"] = "androidUx";
15
+ ProjectType["VELA_XTS"] = "velaXts";
16
+ })(ProjectType || (ProjectType = {}));
17
+ (function (ProjectType) {
18
+ /**
19
+ * 获取项目类型
20
+ *
21
+ * 1. 存在`app/app.xts`:velaXts项目
22
+ * 2. 存在`src/app.ux`
23
+ * 1. `src/manifest.json`文件的 `deviceTypeList` 字段包含`watch`:velaUx
24
+ * 2. 否则:androidUx
25
+ * 3. 否则:velaUx
26
+ * @param projectPath
27
+ * @returns
28
+ */
29
+ function getProjectType(projectPath, src = 'src') {
30
+ var _a;
31
+ const isXts = fs_extra_1.default.existsSync(path_1.default.resolve(projectPath, 'app/app.xts'));
32
+ if (isXts) {
33
+ return ProjectType.VELA_XTS;
34
+ }
35
+ const isUx = fs_extra_1.default.existsSync(path_1.default.resolve(projectPath, src, 'app.ux'));
36
+ if (isUx) {
37
+ const mainfest = fs_extra_1.default.readJSONSync(path_1.default.join(projectPath, src, 'manifest.json'));
38
+ const isVela = (_a = mainfest.deviceTypeList) === null || _a === void 0 ? void 0 : _a.includes('watch');
39
+ return isVela ? ProjectType.VELA_UX : ProjectType.ANDDROID_UX;
40
+ }
41
+ return ProjectType.VELA_UX;
42
+ }
43
+ ProjectType.getProjectType = getProjectType;
44
+ })(ProjectType || (ProjectType = {}));
45
+ exports.default = ProjectType;
package/lib/index.d.ts CHANGED
@@ -1,7 +1,14 @@
1
+ import ColorConsole, { StyleMessage } from './ColorConsole';
1
2
  import MapData from './data/MapData';
2
3
  import PositionError from './data/PositionError';
3
- import { ILog, LOG_LEVEL, Logger } from './interface/ILog';
4
+ import ProjectType from './enum/ProjectType';
5
+ import { ILog, Logger, Loglevel } from './interface/ILog';
4
6
  import IPosition from './interface/IPosition';
7
+ import IRouter, { IRouteItem } from './interface/IRouter';
8
+ import { Dictionary } from './type/Type';
9
+ import CommonUtil, { JSONSchemaType } from './utils/CommonUtil';
10
+ import FileUtil, { MatchType } from './utils/FileUtil';
11
+ import NetworkUtil from './utils/NetworkUtil';
12
+ import StringUtil from './utils/StringUtil';
5
13
  import WrapCallback from './utils/WrapCallback';
6
- export { ILog, IPosition, LOG_LEVEL, Logger, MapData, PositionError, WrapCallback, outputQRCodeOnTerminal };
7
- declare function outputQRCodeOnTerminal(text: string): void;
14
+ export { ColorConsole, CommonUtil, Dictionary, FileUtil, ILog, IPosition, IRouteItem, IRouter, Logger, Loglevel, MapData, NetworkUtil, PositionError, StringUtil, WrapCallback, StyleMessage, JSONSchemaType, MatchType, ProjectType };
package/lib/index.js CHANGED
@@ -3,19 +3,24 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.outputQRCodeOnTerminal = exports.WrapCallback = exports.PositionError = exports.MapData = exports.LOG_LEVEL = void 0;
7
- const qrcode_terminal_1 = __importDefault(require("qrcode-terminal"));
6
+ exports.ProjectType = exports.WrapCallback = exports.StringUtil = exports.PositionError = exports.NetworkUtil = exports.MapData = exports.Loglevel = exports.FileUtil = exports.CommonUtil = exports.ColorConsole = void 0;
8
7
  const ColorConsole_1 = __importDefault(require("./ColorConsole"));
8
+ exports.ColorConsole = ColorConsole_1.default;
9
9
  const MapData_1 = __importDefault(require("./data/MapData"));
10
10
  exports.MapData = MapData_1.default;
11
11
  const PositionError_1 = __importDefault(require("./data/PositionError"));
12
12
  exports.PositionError = PositionError_1.default;
13
+ const ProjectType_1 = __importDefault(require("./enum/ProjectType"));
14
+ exports.ProjectType = ProjectType_1.default;
13
15
  const ILog_1 = require("./interface/ILog");
14
- Object.defineProperty(exports, "LOG_LEVEL", { enumerable: true, get: function () { return ILog_1.LOG_LEVEL; } });
16
+ Object.defineProperty(exports, "Loglevel", { enumerable: true, get: function () { return ILog_1.Loglevel; } });
17
+ const CommonUtil_1 = __importDefault(require("./utils/CommonUtil"));
18
+ exports.CommonUtil = CommonUtil_1.default;
19
+ const FileUtil_1 = __importDefault(require("./utils/FileUtil"));
20
+ exports.FileUtil = FileUtil_1.default;
21
+ const NetworkUtil_1 = __importDefault(require("./utils/NetworkUtil"));
22
+ exports.NetworkUtil = NetworkUtil_1.default;
23
+ const StringUtil_1 = __importDefault(require("./utils/StringUtil"));
24
+ exports.StringUtil = StringUtil_1.default;
15
25
  const WrapCallback_1 = __importDefault(require("./utils/WrapCallback"));
16
26
  exports.WrapCallback = WrapCallback_1.default;
17
- function outputQRCodeOnTerminal(text) {
18
- ColorConsole_1.default.log(`Generate QR code for HTTP server: ${text}`);
19
- qrcode_terminal_1.default.generate(text, { small: true });
20
- }
21
- exports.outputQRCodeOnTerminal = outputQRCodeOnTerminal;
@@ -1,18 +1,18 @@
1
1
  import { StyleMessage } from '../ColorConsole';
2
2
  import IPosition from './IPosition';
3
- export declare enum LOG_LEVEL {
4
- Log = 0,
5
- Success = 1,
6
- Info = 2,
7
- Warn = 3,
8
- Error = 4,
9
- Throw = 5
3
+ export declare enum Loglevel {
4
+ LOG = 0,
5
+ SUCCESS = 1,
6
+ INFO = 2,
7
+ WARN = 3,
8
+ ERROR = 4,
9
+ THROW = 5
10
10
  }
11
11
  /**
12
12
  * ILog
13
13
  */
14
14
  export interface ILog {
15
- level?: LOG_LEVEL;
15
+ level?: Loglevel;
16
16
  message: StyleMessage[] | StyleMessage;
17
17
  position?: IPosition;
18
18
  filePath?: string;
@@ -1,13 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LOG_LEVEL = void 0;
3
+ exports.Loglevel = void 0;
4
4
  // 日志类别
5
- var LOG_LEVEL;
6
- (function (LOG_LEVEL) {
7
- LOG_LEVEL[LOG_LEVEL["Log"] = 0] = "Log";
8
- LOG_LEVEL[LOG_LEVEL["Success"] = 1] = "Success";
9
- LOG_LEVEL[LOG_LEVEL["Info"] = 2] = "Info";
10
- LOG_LEVEL[LOG_LEVEL["Warn"] = 3] = "Warn";
11
- LOG_LEVEL[LOG_LEVEL["Error"] = 4] = "Error";
12
- LOG_LEVEL[LOG_LEVEL["Throw"] = 5] = "Throw";
13
- })(LOG_LEVEL || (exports.LOG_LEVEL = LOG_LEVEL = {}));
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 = {}));
@@ -26,5 +26,9 @@ interface IPosition {
26
26
  * 结束列
27
27
  */
28
28
  endColumn: number;
29
+ /**
30
+ * 节点所在文件
31
+ */
32
+ source?: string;
29
33
  }
30
34
  export default IPosition;
@@ -0,0 +1,30 @@
1
+ import Router from 'koa-router';
2
+ /**
3
+ * IRouter
4
+ */
5
+ interface IRouteItem<STateT = any, CustomT = {}> {
6
+ /**
7
+ * 路径
8
+ */
9
+ path: string;
10
+ /**
11
+ * 请求方法, 默认get
12
+ */
13
+ method?: 'get' | 'post' | 'put' | 'delete';
14
+ /**
15
+ * 处理函数
16
+ */
17
+ handler: Router.IMiddleware<STateT, CustomT>;
18
+ }
19
+ interface IRouter<Param = any> {
20
+ /**
21
+ * 路由的全局参数
22
+ */
23
+ param: Param;
24
+ /**
25
+ * 路由列表
26
+ */
27
+ routeList: IRouteItem[];
28
+ }
29
+ export { IRouteItem };
30
+ export default IRouter;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,5 +1,5 @@
1
- /// <reference types="node" />
2
1
  import { Schema, SomeJTDSchemaType } from 'ajv/dist/core';
2
+ import { ILog } from '../interface/ILog';
3
3
  export type JSONSchemaType = Schema & SomeJTDSchemaType;
4
4
  /**
5
5
  * 不好分类的工具函数
@@ -13,6 +13,7 @@ declare class CommonUtil {
13
13
  * @returns hash 值
14
14
  */
15
15
  static calcDataDigest(buffer: Buffer): Buffer;
16
+ static calcImageDigest(filePath: string): string;
16
17
  /**
17
18
  * 从开发者项目的 node_module 中加载指定依赖;
18
19
  * 如果不存在,提示下载;存在则返回加载的依赖
@@ -39,5 +40,14 @@ declare class CommonUtil {
39
40
  * @returns
40
41
  */
41
42
  static validateJson(json: JSON, schema: JSONSchemaType): Error[] | undefined;
43
+ static outputQRCodeOnTerminal(text: string): Promise<void>;
44
+ /**
45
+ * 终端环境下处理日志列表
46
+ *
47
+ * 1. 用ColorConsole输出日志
48
+ * 2. 如果日志中有Error/Throw,则终止程序
49
+ * @param logs
50
+ */
51
+ static processingLogsInTerminal(logs?: ILog[]): void;
42
52
  }
43
53
  export default CommonUtil;
@@ -7,6 +7,7 @@ const crypto_1 = __importDefault(require("crypto"));
7
7
  const ajv_1 = __importDefault(require("ajv"));
8
8
  const fs_1 = __importDefault(require("fs"));
9
9
  const path_1 = __importDefault(require("path"));
10
+ const qrcode_1 = __importDefault(require("qrcode"));
10
11
  const ColorConsole_1 = __importDefault(require("../ColorConsole"));
11
12
  const ILog_1 = require("../interface/ILog");
12
13
  /**
@@ -25,6 +26,11 @@ class CommonUtil {
25
26
  hash.update(buffer);
26
27
  return hash.digest();
27
28
  }
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);
33
+ }
28
34
  /**
29
35
  * 从开发者项目的 node_module 中加载指定依赖;
30
36
  * 如果不存在,提示下载;存在则返回加载的依赖
@@ -36,12 +42,12 @@ class CommonUtil {
36
42
  return Promise.reject(new Error(ColorConsole_1.default.createMessage([
37
43
  {
38
44
  word: packageName,
39
- style: ColorConsole_1.default.getStyle(ILog_1.LOG_LEVEL.Error)
45
+ style: ColorConsole_1.default.getStyle(ILog_1.Loglevel.ERROR)
40
46
  },
41
47
  'is missing, run',
42
48
  {
43
49
  word: `npm i ${packageName}`,
44
- style: ColorConsole_1.default.getStyle(ILog_1.LOG_LEVEL.Error)
50
+ style: ColorConsole_1.default.getStyle(ILog_1.Loglevel.ERROR)
45
51
  },
46
52
  'to install it'
47
53
  ])));
@@ -92,7 +98,7 @@ class CommonUtil {
92
98
  if (ajv.errors) {
93
99
  const errors = ajv.errors.map((item) => {
94
100
  const { message, instancePath, keyword } = item;
95
- const errorMessage = `${instancePath ? `${instancePath}: ` : ''} ${message}`;
101
+ const errorMessage = `${instancePath ? `${instancePath}: ` : ''}${message}`;
96
102
  if (keyword === 'required') {
97
103
  return new TypeError(errorMessage);
98
104
  }
@@ -101,5 +107,28 @@ class CommonUtil {
101
107
  return errors;
102
108
  }
103
109
  }
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
+ * 终端环境下处理日志列表
117
+ *
118
+ * 1. 用ColorConsole输出日志
119
+ * 2. 如果日志中有Error/Throw,则终止程序
120
+ * @param logs
121
+ */
122
+ static processingLogsInTerminal(logs) {
123
+ if (!logs) {
124
+ return;
125
+ }
126
+ logs.forEach((log) => {
127
+ ColorConsole_1.default.logger(log);
128
+ });
129
+ if (logs.some((log) => log.level === ILog_1.Loglevel.ERROR || log.level === ILog_1.Loglevel.THROW)) {
130
+ process.exit(1);
131
+ }
132
+ }
104
133
  }
105
134
  exports.default = CommonUtil;
@@ -1,3 +1,5 @@
1
+ import Fs from 'fs-extra';
2
+ import { RimrafSyncOptions } from 'rimraf';
1
3
  type OneMatchType = string | RegExp | ((path: string) => boolean);
2
4
  export type MatchType = OneMatchType | OneMatchType[];
3
5
  /**
@@ -51,11 +53,12 @@ declare class FileUtil {
51
53
  static replaceKeywords(content: string, keywordDic: Record<string, string>): string;
52
54
  /**
53
55
  * 更新文件路径
54
- * @param path
55
- * @param fullName
56
+ * @param filePath
57
+ * @param newFileName
56
58
  * @returns
59
+ * @example updateFileName('./a/b/c.ux', 'd.js') 转换结果为'./a/b/d.js'
57
60
  */
58
- static updatePath(path: string, fullName: string): string;
61
+ static updateFileName(filePath: string, newFileName: string): string;
59
62
  /**
60
63
  * 复制文件
61
64
  * @param sourceDir 源目录
@@ -65,9 +68,24 @@ declare class FileUtil {
65
68
  */
66
69
  static copyFiles(sourceDir: string, targetDir: string, excludes?: MatchType, includes?: MatchType): void;
67
70
  /**
68
- * 校验文件
69
- * @param fileList
71
+ * 检查指定的文件列表是否全部存在
72
+ * @param fileList 文件列表
70
73
  */
71
74
  static checkFilePath(fileList: string[]): boolean;
75
+ static del(patterns: string | string[], options?: RimrafSyncOptions): Promise<boolean>;
76
+ /**
77
+ * 创建目录
78
+ *
79
+ * *支持 windows 系统创建隐藏目录
80
+ * @param path
81
+ * @param options
82
+ * @returns
83
+ */
84
+ static mkdirSync(path: Fs.PathLike, options?: Fs.MakeDirectoryOptions & {
85
+ /**
86
+ * 是否为隐藏目录-windows系统有效
87
+ */
88
+ hidden: true;
89
+ }): string | undefined;
72
90
  }
73
91
  export default FileUtil;
@@ -1,11 +1,22 @@
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
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
5
14
  Object.defineProperty(exports, "__esModule", { value: true });
6
15
  const fs_extra_1 = __importDefault(require("fs-extra"));
7
16
  const path_1 = __importDefault(require("path"));
8
- const ColorConsole_1 = __importDefault(require("../ColorConsole"));
17
+ const rimraf_1 = require("rimraf");
18
+ const fswin_1 = __importDefault(require("fswin"));
19
+ const minimatch_1 = require("minimatch");
9
20
  /**
10
21
  * FileUtil
11
22
  */
@@ -41,7 +52,7 @@ class FileUtil {
41
52
  case 'function':
42
53
  return matchType(value);
43
54
  case 'string':
44
- return matchType === value;
55
+ return (0, minimatch_1.minimatch)(value, matchType, { dot: true });
45
56
  case 'object':
46
57
  if (matchType instanceof RegExp) {
47
58
  return matchType.test(value);
@@ -68,9 +79,12 @@ class FileUtil {
68
79
  const result = [];
69
80
  files.forEach((item) => {
70
81
  const itemPath = path_1.default.join(dir, item.name);
71
- if (item.isDirectory() && item) {
72
- const children = this.readAlldirSync(itemPath, includes, excludes);
73
- result.push(...children);
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
+ }
74
88
  }
75
89
  else {
76
90
  if (this.include(itemPath, includes, excludes)) {
@@ -111,15 +125,13 @@ class FileUtil {
111
125
  }
112
126
  /**
113
127
  * 更新文件路径
114
- * @param path
115
- * @param fullName
128
+ * @param filePath
129
+ * @param newFileName
116
130
  * @returns
131
+ * @example updateFileName('./a/b/c.ux', 'd.js') 转换结果为'./a/b/d.js'
117
132
  */
118
- static updatePath(path, fullName) {
119
- if (fs_extra_1.default.statSync(path).isFile()) {
120
- return path_1.default.join(path_1.default.dirname(path), fullName);
121
- }
122
- return path;
133
+ static updateFileName(filePath, newFileName) {
134
+ return filePath && newFileName ? path_1.default.join(path_1.default.dirname(filePath), newFileName) : '';
123
135
  }
124
136
  /**
125
137
  * 复制文件
@@ -129,27 +141,38 @@ class FileUtil {
129
141
  * @param includes 包含的文件
130
142
  */
131
143
  static copyFiles(sourceDir, targetDir, excludes, includes) {
132
- const files = this.readAlldirSync(sourceDir, includes, excludes);
144
+ const files = FileUtil.readAlldirSync(sourceDir, includes, excludes);
133
145
  for (let file of files) {
134
146
  const targetPath = path_1.default.join(targetDir, path_1.default.relative(sourceDir, file));
135
147
  fs_extra_1.default.copySync(file, targetPath, { overwrite: true });
136
148
  }
137
149
  }
138
150
  /**
139
- * 校验文件
140
- * @param fileList
151
+ * 检查指定的文件列表是否全部存在
152
+ * @param fileList 文件列表
141
153
  */
142
154
  static checkFilePath(fileList) {
143
- let checkPass = true;
144
- fileList.forEach((filePath) => {
145
- if (!fs_extra_1.default.existsSync(filePath)) {
146
- const fileName = path_1.default.basename(filePath);
147
- const dirPath = path_1.default.dirname(filePath);
148
- ColorConsole_1.default.error(`Error: File ${fileName} does not exist in the path:${dirPath}`);
149
- checkPass = false;
150
- }
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));
151
160
  });
152
- return checkPass;
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 });
174
+ }
175
+ return result;
153
176
  }
154
177
  }
155
178
  exports.default = FileUtil;
@@ -1,3 +1,7 @@
1
+ import Koa from 'koa';
2
+ import { default as Router } from 'koa-router';
3
+ import { Server } from 'net';
4
+ import IRouter from '../interface/IRouter';
1
5
  /**
2
6
  * NetworkUtil
3
7
  */
@@ -10,5 +14,52 @@ declare class NetworkUtil {
10
14
  * @returns
11
15
  */
12
16
  static gitClone(url: string, localPath: string, showProgress?: boolean): Promise<void>;
17
+ /**
18
+ * 创建 http 服务器
19
+ * @param data
20
+ * @returns
21
+ */
22
+ static createHttpServer(data: {
23
+ /**
24
+ * 期望的端口
25
+ */
26
+ wantPort?: number;
27
+ /**
28
+ * 路由列表
29
+ */
30
+ routeConfigList: IRouter[];
31
+ staticFolder?: string;
32
+ /**
33
+ * 事件
34
+ */
35
+ events?: {
36
+ onSuccess?: (port: number) => void;
37
+ };
38
+ }): Promise<{
39
+ /**
40
+ * sever实例
41
+ */
42
+ server: Server;
43
+ /**
44
+ * 实际使用的端口
45
+ */
46
+ port: number;
47
+ app: Koa;
48
+ }>;
49
+ static getIPv4IPAddress(): string | undefined;
50
+ /**
51
+ * 从请求中获取客户端 ip
52
+ * @param ctx koa的请求上下文
53
+ * @returns
54
+ */
55
+ static getClientIp(ctx: Router.RouterContext): string | undefined;
56
+ /**
57
+ * 从网络地址中获取真实 ip
58
+ *
59
+ * @example
60
+ * @param ip
61
+ * @returns
62
+ */
63
+ static stripPrefixForIPV4MappedIPV6Address(ip: string): string;
13
64
  }
14
65
  export default NetworkUtil;
@@ -1,10 +1,24 @@
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
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
5
14
  Object.defineProperty(exports, "__esModule", { value: true });
6
15
  const ansi_colors_1 = __importDefault(require("ansi-colors"));
7
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"));
8
22
  const simple_git_1 = __importDefault(require("simple-git"));
9
23
  /**
10
24
  * NetworkUtil
@@ -48,5 +62,82 @@ class NetworkUtil {
48
62
  });
49
63
  });
50
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;
100
+ }
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
+ }
110
+ }
111
+ }
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
+ }
125
+ }
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(/^.*:/, '');
139
+ }
140
+ return ip;
141
+ }
51
142
  }
52
143
  exports.default = NetworkUtil;
@@ -13,7 +13,7 @@ declare class StringUtil {
13
13
  */
14
14
  static hyphenedToCamel(value: string): string;
15
15
  /** 首字母大写 */
16
- static capitalizeFirstLetter([first, ...rest]: string): string;
16
+ static capitalizeFirstLetter(str: string): string;
17
17
  /** 逗号分割的字符串转数组 */
18
18
  static string2arrayByComma(value?: string): string[];
19
19
  /**
@@ -22,7 +22,7 @@ declare class StringUtil {
22
22
  * @param styleTransform 是否为style解析树的数组转换
23
23
  * @returns
24
24
  */
25
- static arrayTostring(arr: any[], styleTransform?: boolean): string;
25
+ static arrayToString(arr: any[]): string;
26
26
  /**
27
27
  * 对象转字符串
28
28
  * @param obj
@@ -31,6 +31,6 @@ declare class StringUtil {
31
31
  */
32
32
  static objectToString(obj: {
33
33
  [key: string]: any;
34
- }, styleTransform?: boolean): string;
34
+ }): string;
35
35
  }
36
36
  export default StringUtil;
@@ -19,8 +19,10 @@ class StringUtil {
19
19
  return value === null || value === void 0 ? void 0 : value.replace(/-([a-z])/g, (_, match) => match.toUpperCase());
20
20
  }
21
21
  /** 首字母大写 */
22
- static capitalizeFirstLetter([first, ...rest]) {
23
- return [first.toUpperCase(), ...rest].join('');
22
+ static capitalizeFirstLetter(str) {
23
+ if (!str)
24
+ return '';
25
+ return str.charAt(0).toUpperCase() + str.slice(1);
24
26
  }
25
27
  /** 逗号分割的字符串转数组 */
26
28
  static string2arrayByComma(value) {
@@ -34,7 +36,7 @@ class StringUtil {
34
36
  * @param styleTransform 是否为style解析树的数组转换
35
37
  * @returns
36
38
  */
37
- static arrayTostring(arr, styleTransform = false) {
39
+ static arrayToString(arr) {
38
40
  if (Array.isArray(arr)) {
39
41
  if (arr.length <= 0) {
40
42
  return '[]';
@@ -48,10 +50,10 @@ class StringUtil {
48
50
  switch (typeof item) {
49
51
  case 'object':
50
52
  if (Array.isArray(item)) {
51
- valueStr = StringUtil.arrayTostring(item, styleTransform);
53
+ valueStr = StringUtil.arrayToString(item);
52
54
  }
53
55
  else {
54
- valueStr = StringUtil.objectToString(item, styleTransform);
56
+ valueStr = StringUtil.objectToString(item);
55
57
  }
56
58
  break;
57
59
  case 'string':
@@ -71,9 +73,8 @@ class StringUtil {
71
73
  * @param styleTransform 是否为style解析树的数组转换
72
74
  * @returns
73
75
  */
74
- static objectToString(obj, styleTransform = false) {
75
- return `{
76
- ${Object.keys(obj)
76
+ static objectToString(obj) {
77
+ return `{${Object.keys(obj)
77
78
  .map((key) => {
78
79
  const value = obj[key];
79
80
  if (value === undefined) {
@@ -83,36 +84,23 @@ class StringUtil {
83
84
  switch (typeof value) {
84
85
  case 'object':
85
86
  if (Array.isArray(value)) {
86
- valueStr = StringUtil.arrayTostring(value, styleTransform);
87
+ valueStr = StringUtil.arrayToString(value);
87
88
  }
88
89
  else {
89
- valueStr = StringUtil.objectToString(value, styleTransform);
90
+ valueStr = StringUtil.objectToString(value);
90
91
  }
91
92
  break;
92
93
  case 'function':
93
94
  valueStr = value.toString();
94
95
  break;
95
- case 'string':
96
- if (styleTransform) {
97
- // 匹配require函数调用
98
- const testReg = new RegExp(/require\(['"](.+?)['"]\)/g);
99
- if (testReg.test(value)) {
100
- valueStr = value;
101
- }
102
- else {
103
- valueStr = JSON.stringify(value);
104
- }
105
- break;
106
- }
107
96
  default:
108
97
  valueStr = value;
109
98
  break;
110
99
  }
111
- return `${StringUtil.hyphenedToCamel(key)}:${valueStr}`;
100
+ return `"${key}":${valueStr}`;
112
101
  })
113
102
  .filter((item) => Boolean(item))
114
- .join(',')}
115
- }`;
103
+ .join(',\n')}}`;
116
104
  }
117
105
  }
118
106
  exports.default = StringUtil;
@@ -21,7 +21,7 @@ class WrapCallback {
21
21
  onLog(log);
22
22
  // 2. 对throw和error进行错误抛出
23
23
  const { level, message, position } = log;
24
- if (level === ILog_1.LOG_LEVEL.Error || level === ILog_1.LOG_LEVEL.Throw) {
24
+ if (level === ILog_1.Loglevel.ERROR || level === ILog_1.Loglevel.THROW) {
25
25
  if (position) {
26
26
  throw new PositionError_1.default(position, ColorConsole_1.default.createMessage(message));
27
27
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiot-toolkit/shared-utils",
3
- "version": "2.0.2-dev.7",
3
+ "version": "2.0.2",
4
4
  "description": "The common method functions of the aiot-toolkit.",
5
5
  "homepage": "",
6
6
  "license": "ISC",
@@ -17,13 +17,29 @@
17
17
  },
18
18
  "dependencies": {
19
19
  "ajv": "^8.12.0",
20
+ "ansi-colors": "^4.1.3",
20
21
  "chalk": "^4.0.0",
22
+ "cli-progress": "^3.12.0",
21
23
  "dayjs": "^1.11.9",
22
24
  "fs-extra": "^11.2.0",
23
- "qrcode-terminal": "^0.12.0"
25
+ "fswin": "^3.24.829",
26
+ "koa": "^2.15.3",
27
+ "koa-router": "^13.0.1",
28
+ "koa-static": "^5.0.0",
29
+ "minimatch": "^10.0.1",
30
+ "portfinder": "^1.0.32",
31
+ "qrcode": "^1.5.4",
32
+ "rimraf": "^5.0.9",
33
+ "simple-git": "^3.25.0"
24
34
  },
25
35
  "devDependencies": {
26
- "@types/qrcode-terminal": "^0.12.0"
36
+ "@types/cli-progress": "^3.11.6",
37
+ "@types/fs-extra": "^11.0.4",
38
+ "@types/koa": "^2.15.0",
39
+ "@types/koa-router": "^7.4.8",
40
+ "@types/koa-static": "^4.0.4",
41
+ "@types/minimatch": "^5.1.2",
42
+ "@types/qrcode": "^1.5.5"
27
43
  },
28
- "gitHead": "26fa71dd55c1f68727ccc2d627a40822074b8ba1"
44
+ "gitHead": "8ca4bf2ed7bcf11911e5c514696951bdba4fc12d"
29
45
  }