@aiot-toolkit/shared-utils 2.0.2-beta.10 → 2.0.2-beta.11

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,4 +1,4 @@
1
- import { ILog, LOG_LEVEL } from './interface/ILog';
1
+ import { ILog, Loglevel } from './interface/ILog';
2
2
  interface IStyle {
3
3
  color?: string;
4
4
  bgColor?: string;
@@ -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
  * 创建复杂格式的消息,可单独设置词语样式
@@ -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,17 @@
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
+ * @param projectPath
13
+ * @returns
14
+ */
15
+ function getProjectType(projectPath: string, src?: string): ProjectType;
16
+ }
17
+ export default ProjectType;
@@ -0,0 +1,39 @@
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
+ * @param projectPath
21
+ * @returns
22
+ */
23
+ function getProjectType(projectPath, src = 'src') {
24
+ var _a;
25
+ const isXts = fs_extra_1.default.existsSync(path_1.default.resolve(projectPath, 'app/app.xts'));
26
+ if (isXts) {
27
+ return ProjectType.VELA_XTS;
28
+ }
29
+ const isUx = fs_extra_1.default.existsSync(path_1.default.resolve(projectPath, 'src/app.ux'));
30
+ if (isUx) {
31
+ const mainfest = fs_extra_1.default.readJSONSync(path_1.default.join(projectPath, src, 'manifest.json'));
32
+ const isVela = (_a = mainfest.deviceTypeList) === null || _a === void 0 ? void 0 : _a.includes('watch');
33
+ return isVela ? ProjectType.VELA_UX : ProjectType.ANDDROID_UX;
34
+ }
35
+ return ProjectType.VELA_UX;
36
+ }
37
+ ProjectType.getProjectType = getProjectType;
38
+ })(ProjectType || (ProjectType = {}));
39
+ 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 = {}));
@@ -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,6 @@
1
1
  /// <reference types="node" />
2
2
  import { Schema, SomeJTDSchemaType } from 'ajv/dist/core';
3
+ import { ILog } from '../interface/ILog';
3
4
  export type JSONSchemaType = Schema & SomeJTDSchemaType;
4
5
  /**
5
6
  * 不好分类的工具函数
@@ -40,5 +41,14 @@ declare class CommonUtil {
40
41
  * @returns
41
42
  */
42
43
  static validateJson(json: JSON, schema: JSONSchemaType): Error[] | undefined;
44
+ static outputQRCodeOnTerminal(text: string): void;
45
+ /**
46
+ * 终端环境下处理日志列表
47
+ *
48
+ * 1. 用ColorConsole输出日志
49
+ * 2. 如果日志中有Error/Throw,则终止程序
50
+ * @param logs
51
+ */
52
+ static processingLogsInTerminal(logs?: ILog[]): void;
43
53
  }
44
54
  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_terminal_1 = __importDefault(require("qrcode-terminal"));
10
11
  const ColorConsole_1 = __importDefault(require("../ColorConsole"));
11
12
  const ILog_1 = require("../interface/ILog");
12
13
  /**
@@ -41,12 +42,12 @@ class CommonUtil {
41
42
  return Promise.reject(new Error(ColorConsole_1.default.createMessage([
42
43
  {
43
44
  word: packageName,
44
- style: ColorConsole_1.default.getStyle(ILog_1.LOG_LEVEL.Error)
45
+ style: ColorConsole_1.default.getStyle(ILog_1.Loglevel.ERROR)
45
46
  },
46
47
  'is missing, run',
47
48
  {
48
49
  word: `npm i ${packageName}`,
49
- style: ColorConsole_1.default.getStyle(ILog_1.LOG_LEVEL.Error)
50
+ style: ColorConsole_1.default.getStyle(ILog_1.Loglevel.ERROR)
50
51
  },
51
52
  'to install it'
52
53
  ])));
@@ -106,5 +107,26 @@ class CommonUtil {
106
107
  return errors;
107
108
  }
108
109
  }
110
+ static outputQRCodeOnTerminal(text) {
111
+ qrcode_terminal_1.default.generate(text, { small: true });
112
+ }
113
+ /**
114
+ * 终端环境下处理日志列表
115
+ *
116
+ * 1. 用ColorConsole输出日志
117
+ * 2. 如果日志中有Error/Throw,则终止程序
118
+ * @param logs
119
+ */
120
+ static processingLogsInTerminal(logs) {
121
+ if (!logs) {
122
+ return;
123
+ }
124
+ logs.forEach((log) => {
125
+ ColorConsole_1.default.logger(log);
126
+ });
127
+ if (logs.some((log) => log.level === ILog_1.Loglevel.ERROR || log.level === ILog_1.Loglevel.THROW)) {
128
+ process.exit(1);
129
+ }
130
+ }
109
131
  }
110
132
  exports.default = CommonUtil;
@@ -51,11 +51,12 @@ declare class FileUtil {
51
51
  static replaceKeywords(content: string, keywordDic: Record<string, string>): string;
52
52
  /**
53
53
  * 更新文件路径
54
- * @param path
55
- * @param fullName
54
+ * @param filePath
55
+ * @param newFileName
56
56
  * @returns
57
+ * @example updateFileName('./a/b/c.ux', 'd.js') 转换结果为'./a/b/d.js'
57
58
  */
58
- static updatePath(path: string, fullName: string): string;
59
+ static updateFileName(filePath: string, newFileName: string): string;
59
60
  /**
60
61
  * 复制文件
61
62
  * @param sourceDir 源目录
@@ -5,7 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  const fs_extra_1 = __importDefault(require("fs-extra"));
7
7
  const path_1 = __importDefault(require("path"));
8
- const ColorConsole_1 = __importDefault(require("../ColorConsole"));
9
8
  /**
10
9
  * FileUtil
11
10
  */
@@ -111,12 +110,13 @@ class FileUtil {
111
110
  }
112
111
  /**
113
112
  * 更新文件路径
114
- * @param path
115
- * @param fullName
113
+ * @param filePath
114
+ * @param newFileName
116
115
  * @returns
116
+ * @example updateFileName('./a/b/c.ux', 'd.js') 转换结果为'./a/b/d.js'
117
117
  */
118
- static updatePath(path, fullName) {
119
- return path_1.default.join(path_1.default.dirname(path), fullName);
118
+ static updateFileName(filePath, newFileName) {
119
+ return filePath && newFileName ? path_1.default.join(path_1.default.dirname(filePath), newFileName) : '';
120
120
  }
121
121
  /**
122
122
  * 复制文件
@@ -126,7 +126,7 @@ class FileUtil {
126
126
  * @param includes 包含的文件
127
127
  */
128
128
  static copyFiles(sourceDir, targetDir, excludes, includes) {
129
- const files = this.readAlldirSync(sourceDir, includes, excludes);
129
+ const files = FileUtil.readAlldirSync(sourceDir, includes, excludes);
130
130
  for (let file of files) {
131
131
  const targetPath = path_1.default.join(targetDir, path_1.default.relative(sourceDir, file));
132
132
  fs_extra_1.default.copySync(file, targetPath, { overwrite: true });
@@ -140,9 +140,6 @@ class FileUtil {
140
140
  let checkPass = true;
141
141
  fileList.forEach((filePath) => {
142
142
  if (!fs_extra_1.default.existsSync(filePath)) {
143
- const fileName = path_1.default.basename(filePath);
144
- const dirPath = path_1.default.dirname(filePath);
145
- ColorConsole_1.default.error(`Error: File ${fileName} does not exist in the path:${dirPath}`);
146
143
  checkPass = false;
147
144
  }
148
145
  });
@@ -1,3 +1,8 @@
1
+ /// <reference types="node" />
2
+ import Koa from 'koa';
3
+ import { default as Router } from 'koa-router';
4
+ import { Server } from 'net';
5
+ import IRouter from '../interface/IRouter';
1
6
  /**
2
7
  * NetworkUtil
3
8
  */
@@ -10,5 +15,52 @@ declare class NetworkUtil {
10
15
  * @returns
11
16
  */
12
17
  static gitClone(url: string, localPath: string, showProgress?: boolean): Promise<void>;
18
+ /**
19
+ * 创建 http 服务器
20
+ * @param data
21
+ * @returns
22
+ */
23
+ static createHttpServer(data: {
24
+ /**
25
+ * 期望的端口
26
+ */
27
+ wantPort?: number;
28
+ /**
29
+ * 路由列表
30
+ */
31
+ routeConfigList: IRouter[];
32
+ staticFolder?: string;
33
+ /**
34
+ * 事件
35
+ */
36
+ events?: {
37
+ onSuccess?: (port: number) => void;
38
+ };
39
+ }): Promise<{
40
+ /**
41
+ * sever实例
42
+ */
43
+ server: Server;
44
+ /**
45
+ * 实际使用的端口
46
+ */
47
+ port: number;
48
+ app: Koa;
49
+ }>;
50
+ static getIPv4IPAddress(): string | undefined;
51
+ /**
52
+ * 从请求中获取客户端 ip
53
+ * @param ctx koa的请求上下文
54
+ * @returns
55
+ */
56
+ static getClientIp(ctx: Router.RouterContext): string | undefined;
57
+ /**
58
+ * 从网络地址中获取真实 ip
59
+ *
60
+ * @example
61
+ * @param ip
62
+ * @returns
63
+ */
64
+ static stripPrefixForIPV4MappedIPV6Address(ip: string): string;
13
65
  }
14
66
  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-beta.10",
3
+ "version": "2.0.2-beta.11",
4
4
  "description": "The common method functions of the aiot-toolkit.",
5
5
  "homepage": "",
6
6
  "license": "ISC",
@@ -20,11 +20,18 @@
20
20
  "chalk": "^4.0.0",
21
21
  "dayjs": "^1.11.9",
22
22
  "fs-extra": "^11.2.0",
23
+ "koa": "^2.15.3",
24
+ "koa-router": "^12.0.1",
25
+ "koa-static": "^5.0.0",
26
+ "portfinder": "^1.0.32",
23
27
  "qrcode-terminal": "^0.12.0"
24
28
  },
25
29
  "devDependencies": {
26
30
  "@types/fs-extra": "^11.0.4",
31
+ "@types/koa": "^2.15.0",
32
+ "@types/koa-router": "^7.4.8",
33
+ "@types/koa-static": "^4.0.4",
27
34
  "@types/qrcode-terminal": "^0.12.0"
28
35
  },
29
- "gitHead": "00d23c1ad1306a6c72bb007685de9fd4a6ee61af"
36
+ "gitHead": "07c38dd12ba0d932c6dc1fd16fe25aaf15ab9fbb"
30
37
  }