@x-9lab/xlab 1.0.0-alpha.3 → 1.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.
@@ -57,21 +57,21 @@ export { fix0 };
57
57
  /**
58
58
  * 格式化时间
59
59
  * @param format 日期格式
60
- * @param date 时间戳
60
+ * @param ts 时间戳
61
61
  * @return 格式化后的时间
62
62
  */
63
63
  declare function date(format: string, ts: number): string;
64
64
  /**
65
65
  * 格式化时间
66
66
  * @param format 日期格式
67
- * @param date 日期字符串
67
+ * @param ts 日期字符串
68
68
  * @return 格式化后的时间
69
69
  */
70
70
  declare function date(format: string, ts: string): string;
71
71
  /**
72
72
  * 格式化时间
73
73
  * @param format 日期格式
74
- * @param date 日期对象
74
+ * @param ts 日期对象
75
75
  * @return 格式化后的时间
76
76
  */
77
77
  declare function date(format: string, ts: Date): string;
@@ -125,6 +125,7 @@ declare function promiseWapper(...args: any[]): Promise<unknown>;
125
125
  export { promiseWapper };
126
126
  /**
127
127
  * 封装一个 promise 形式的 request 方法
128
+ * @deprecated 请直接使用 component 中的 request 模块
128
129
  */
129
130
  declare function requestWapper<T = any>(...args: any[]): Promise<unknown>;
130
131
  export { requestWapper };
@@ -167,3 +168,16 @@ export { checkFileStat };
167
168
  /**获取真正可执行的模块 */
168
169
  declare function getRealDefaultMod(mod: any): any;
169
170
  export { getRealDefaultMod };
171
+ /**
172
+ * 休眠随机时间
173
+ * @param time 随机时间范围
174
+ * @property min 最小时间(ms)
175
+ * @property max 最大时间(ms)
176
+ */
177
+ declare function sleep(time: [min: number, max: number]): Promise<boolean>;
178
+ /**
179
+ * 休眠
180
+ * @param time 休眠时间(ms)
181
+ */
182
+ declare function sleep(time: number): Promise<boolean>;
183
+ export { sleep };
File without changes
@@ -0,0 +1,42 @@
1
+ /**内置组件 */
2
+ interface InternalComponents {
3
+ /**资产 */
4
+ assets: typeof import("./assets");
5
+ /**缓存 */
6
+ cache: typeof import("./cache");
7
+ /**cluster */
8
+ cluster: typeof import("./cluster");
9
+ /**Http header 相关 */
10
+ header: typeof import("./header");
11
+ /**Html 内容处理器 */
12
+ "html-processor": typeof import("./html-processor");
13
+ /**JS 内容处理器 */
14
+ "js-processor": typeof import("./js-processor");
15
+ /**数据注入 */
16
+ injection: typeof import("./injection");
17
+ /**MD5 */
18
+ md5: typeof import("./md5");
19
+ /**MIME */
20
+ mime: typeof import("./mime");
21
+ /**客户端判断 */
22
+ platform: typeof import("./platform");
23
+ /**请求参数处理 */
24
+ querystring: typeof import("./querystring");
25
+ /**各种重定向方法 */
26
+ redirect: typeof import("./redirect");
27
+ /**简单的 uuid */
28
+ uuid: typeof import("./uuid");
29
+ /**版本比对 */
30
+ version: typeof import("./version");
31
+ /**定时任务 */
32
+ cron: typeof import("./cron");
33
+ /**日志 */
34
+ log: typeof import("./log");
35
+ /**业务返回码 */
36
+ "return-code": typeof import("./return-code");
37
+ /**通用工具函数集 */
38
+ common: typeof import("./common");
39
+ /**内部请求模块 */
40
+ request: typeof import("./request");
41
+ }
42
+ export type { InternalComponents };
File without changes
@@ -0,0 +1,51 @@
1
+ import type { RequestInit } from "node-fetch";
2
+ /**支持的返回数据类型 */
3
+ declare type IFetchType = "text" | "json" | "blob" | "buffer" | "arrayBuffer";
4
+ /**请求配置 */
5
+ interface IFetchConfig extends Partial<Omit<RequestInit, "body" | "method">> {
6
+ /**数据返回类型 */
7
+ type?: IFetchType;
8
+ /**是否强制同源 */
9
+ sameOrigin?: boolean;
10
+ /**请求自动重试次数 */
11
+ retry?: number;
12
+ /**自动重试间隔时间 */
13
+ retryDelay?: number;
14
+ /**是否自动追加随机数retry,默认 false */
15
+ random?: boolean;
16
+ /**数据返回时的钩子 */
17
+ onResponse?: (res?: Response) => Promise<unknown>;
18
+ }
19
+ export type { IFetchConfig };
20
+ /**给指定对象增加一个随机字符串 */
21
+ declare function setRandomStr(query: any): void;
22
+ export { setRandomStr };
23
+ /**设置默认 Headers */
24
+ declare function setDefHeaders(headers: Record<string, any>): void;
25
+ export { setDefHeaders };
26
+ /**
27
+ * 获取数据
28
+ * @param type 请求类型
29
+ * @param uri 请求地址
30
+ * @param query 请求参数
31
+ * @param data 发送数据
32
+ * @param config 请求配置
33
+ * @param needProcessConfig 是否需要处理配置
34
+ */
35
+ declare function httpFetch<T = unknown>(type: string, uri: string, query?: Record<string, any>, data?: any, config?: IFetchConfig, retry?: number, needProcessConfig?: boolean): any;
36
+ export { httpFetch as fetch };
37
+ /**
38
+ * 发起一个 get 请求
39
+ * @param uri 请求地址
40
+ * @param query 请求参数
41
+ */
42
+ declare function requsetGet<T = unknown>(uri: string, query?: Record<string, any>, config?: IFetchConfig): Promise<any>;
43
+ export { requsetGet as get };
44
+ /**
45
+ * 发起一个 post 请求
46
+ * @param uri 请求地址
47
+ * @param query 请求参数
48
+ * @param data 请求数据
49
+ */
50
+ declare function requestPost<T>(uri: string, query?: any, data?: any, config?: IFetchConfig): Promise<any>;
51
+ export { requestPost as post };
@@ -0,0 +1,6 @@
1
+ /**
2
+ * 解析请求别名
3
+ * @param uri 请求地址
4
+ */
5
+ declare function resolve(uri: string): string;
6
+ export default resolve;
@@ -1,27 +1,6 @@
1
+ import type { InternalComponents } from "./components";
1
2
  export type { IPlat } from "./components/platform";
2
3
  import type Koa from "koa";
3
- /**内置组件 */
4
- interface InternalComponents {
5
- assets: typeof import("./components/assets");
6
- cache: typeof import("./components/cache");
7
- cluster: typeof import("./components/cluster");
8
- combo: typeof import("./components/combo");
9
- header: typeof import("./components/header");
10
- "html-processor": typeof import("./components/html-processor");
11
- injection: typeof import("./components/injection");
12
- "js-processor": typeof import("./components/js-processor");
13
- md5: typeof import("./components/md5");
14
- mime: typeof import("./components/mime");
15
- platform: typeof import("./components/platform");
16
- querystring: typeof import("./components/querystring");
17
- redirect: typeof import("./components/redirect");
18
- uuid: typeof import("./components/uuid");
19
- version: typeof import("./components/version");
20
- cron: typeof import("./components/cron");
21
- log: typeof import("./components/log");
22
- "return-code": typeof import("./components/return-code");
23
- common: typeof import("./components/common");
24
- }
25
4
  declare global {
26
5
  /**全局日志对象 */
27
6
  var log: any;
@@ -137,6 +116,10 @@ declare global {
137
116
  strictSSL?: boolean;
138
117
  /**页端注入的 api 设置 */
139
118
  apis?: Record<string, string>;
119
+ /**内部服务域名 */
120
+ internalServers?: Record<string, string>;
121
+ /**内部服务地址 */
122
+ internalApis?: Record<string, string>;
140
123
  /**服务 ip 地址 */
141
124
  ip?: string;
142
125
  /**本地是否存在本地开发配置文件 config.lo.json */
package/README.md CHANGED
@@ -14,6 +14,19 @@ X-9lab 通用服务端
14
14
  }
15
15
  }
16
16
  ```
17
+ - `watch` 模式
18
+ `xlab` 支持自动重启业务,开发中使用该功能可以减少大量手动重启业务的操作。
19
+ 启用方式:
20
+ - 启动命令使用 `w` 参数
21
+ - 在配置文件中开启
22
+ ```js
23
+ const { NODE_ENV } = process.env;
24
+ module.exports = {
25
+ "watch": {
26
+ "enable": NODE_ENV === "development"
27
+ }
28
+ }
29
+ ```
17
30
  - 除了静态资源,服务端业务需要放在项目根目录下的 `@server` 目录中
18
31
  - 支持业务自定义以下内容 (无特殊说明的都是存放在 @server 目录中)
19
32
  - 配置项,存放于 `@config` 目录
@@ -83,14 +96,55 @@ X-9lab 通用服务端
83
96
  function setSysConfig(conf: XLab.IConfig): void;
84
97
  ```
85
98
  - `requireModel` 全局获取 model 的方法
99
+ 该方法只是为获取 model 提供一个快捷方式,也可以通过正常的方式去 require
100
+ - 存放路径 `business/@models`
101
+ - 使用方式
102
+ ```js
103
+ const { testModel } = requireModel("test");
104
+ ```
105
+ - 类型支持
106
+ 由于 `requireModel` 是一个 `xlab` 的内置方法没有业务本身的 model 定义,因此需要业务方自行追加。出于管理方面的考虑,建议将所有的 model 定义放在一个文件中
107
+ ```ts
108
+ declare global {
109
+ namespace XLab {
110
+ interface IModels {
111
+ /**测试 model */
112
+ test: typeof import("./business/@models/test");
113
+ }
114
+ }
115
+ }
116
+ export { }
117
+ ```
86
118
  - `requireService` 全局获取 service 的方法
119
+ 该方法只是为获取 service 提供一个快捷方式,也可以通过正常的方式去 require
120
+ - 存放路径 `business/@services`
121
+ - 使用方式
122
+ ```js
123
+ const { testFn } = requireService("test");
124
+ ```
125
+ - 类型支持
126
+ 由于 `requireService` 是一个 `xlab` 的内置方法没有业务本身的 service 定义,因此需要业务方自行追加。出于管理方面的考虑,建议将所有的 service 定义放在一个文件中
127
+ ```ts
128
+ declare global {
129
+ namespace XLab {
130
+ interface IServices {
131
+ /**测试 model */
132
+ test: typeof import("./business/@services/test");
133
+ }
134
+ }
135
+ }
136
+ export { }
137
+ ```
87
138
 
88
139
  #### Namespace `XLab`
89
140
  `XLab` 提供了一些标准化的定义及系统配置
90
141
  - `IStdRes` 标准返回数据
91
142
  - `IConfig` 系统配置对象
143
+ - 外部模块追加配置项
92
144
  - `ICodeItem` 错误信息对象
93
145
  - `ICodeDetail` 错误定义
146
+ - `IServices` 业务 services 定义
147
+ - `IModels` 业务 model 定义
94
148
 
95
149
  ### 配置项
96
150
  |名称|类型|默认值|说明|
package/dist/bin/watch.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  const { date } = require("@x-drive/utils");
3
3
  const crossSpawn = require("cross-spawn");
4
- colors = require("colors/safe");
4
+ const colors = require("colors/safe");
5
5
  const path = require("path");
6
6
  const fs = require("fs");
7
7
  /**输出内容名称 */ const X_LAB_STR = colors.bold(colors.cyan("🛸 XLab"));
package/dist/bin/xlab CHANGED
@@ -16,34 +16,38 @@ const cli = new Liftoff({
16
16
 
17
17
  const hasWatch = argv.w || argv.watch;
18
18
 
19
- cli.launch(
19
+ function onLaunch(env) {
20
+ let config = {
21
+ "watch": {
22
+ "enable": false
23
+ }
24
+ }
25
+ if (env.configPath) {
26
+ try {
27
+ let customConfig = require(env.configPath);
28
+ if (customConfig) {
29
+ merge(config, customConfig);
30
+ }
31
+ } catch (e) { }
32
+ }
33
+ if (hasWatch) {
34
+ config.watch.enable = true;
35
+ }
36
+ if (config.watch && config.watch.enable) {
37
+ const watch = require("./watch");
38
+ watch(config.watch);
39
+ } else {
40
+ const server = require("../server");
41
+ server.boot();
42
+ }
43
+ }
44
+
45
+ cli.prepare(
20
46
  {
21
47
  "cwd": argv.r || argv.root
22
48
  , "configPath": argv.f || argv.file
23
49
  }
24
50
  , function (env) {
25
- let config = {
26
- "watch": {
27
- "enable": false
28
- }
29
- }
30
- if (env.configPath) {
31
- try {
32
- let customConfig = require(env.configPath);
33
- if (customConfig) {
34
- merge(config, customConfig);
35
- }
36
- } catch (e) { }
37
- }
38
- if (hasWatch) {
39
- config.watch.enable = true;
40
- }
41
- if (config.watch && config.watch.enable) {
42
- const watch = require("./watch");
43
- watch(config.watch);
44
- } else {
45
- const server = require("../server");
46
- server.boot();
47
- }
51
+ cli.execute(env, onLaunch);
48
52
  }
49
53
  );
@@ -26,12 +26,12 @@ _export(exports, {
26
26
  toJsonp: ()=>toJsonp,
27
27
  walk: ()=>walk,
28
28
  checkFileStat: ()=>checkFileStat,
29
- getRealDefaultMod: ()=>getRealDefaultMod
29
+ getRealDefaultMod: ()=>getRealDefaultMod,
30
+ sleep: ()=>sleep
30
31
  });
31
- const _returnCode = require("./return-code");
32
32
  const _utils = require("@x-drive/utils");
33
+ const _returnCode = require("../return-code");
33
34
  const _querystring = /*#__PURE__*/ _interopRequireDefault(require("querystring"));
34
- const _request = /*#__PURE__*/ _interopRequireDefault(require("request"));
35
35
  const _crypto = /*#__PURE__*/ _interopRequireDefault(require("crypto"));
36
36
  const _path = /*#__PURE__*/ _interopRequireDefault(require("path"));
37
37
  const _fs = /*#__PURE__*/ _interopRequireDefault(require("fs"));
@@ -41,6 +41,12 @@ function _interopRequireDefault(obj) {
41
41
  };
42
42
  }
43
43
  var logger;
44
+ function checkLogger() {
45
+ if (!logger) {
46
+ logger = log.getLogger("common");
47
+ }
48
+ return logger;
49
+ }
44
50
  /**
45
51
  * ascii字符串转为base64字符串
46
52
  * @param str 要转化的字符串
@@ -139,7 +145,7 @@ const format_exp = /[YymndjNwaAghGHis]/g;
139
145
  /**
140
146
  * 格式化时间
141
147
  * @param format 日期格式
142
- * @param date 日期数据(时间戳, 字符串)
148
+ * @param ts 日期数据(时间戳, 字符串)
143
149
  * @return 格式化后的时间
144
150
  */ function date(format, ts) {
145
151
  ts = new Date(ts);
@@ -241,16 +247,10 @@ const format_exp = /[YymndjNwaAghGHis]/g;
241
247
  }
242
248
  /**
243
249
  * 封装一个 promise 形式的 request 方法
250
+ * @deprecated 请直接使用 component 中的 request 模块
244
251
  */ function requestWapper(...args) {
245
- return new Promise(function(resolve, reject) {
246
- args.push(function(err, res, body) {
247
- if (err) {
248
- reject(err);
249
- } else {
250
- resolve(body);
251
- }
252
- });
253
- _request.default.apply(_request.default, args);
252
+ return new Promise(function(_, reject) {
253
+ reject(new Error("请直接使用 component 中的 request 模块"));
254
254
  });
255
255
  }
256
256
  /**
@@ -262,9 +262,7 @@ const format_exp = /[YymndjNwaAghGHis]/g;
262
262
  try {
263
263
  re = JSON.parse(data);
264
264
  } catch (err) {
265
- if (!logger) {
266
- log.getLogger("common");
267
- }
265
+ checkLogger();
268
266
  logger.error("Pares create menu return data fail.", data);
269
267
  return null;
270
268
  }
@@ -323,3 +321,13 @@ const format_exp = /[YymndjNwaAghGHis]/g;
323
321
  }
324
322
  return mod;
325
323
  }
324
+ async function sleep(time) {
325
+ const delay = (0, _utils.isArray)(time) ? (0, _utils.random)(time[1], time[0]) : time;
326
+ checkLogger();
327
+ logger.log(`Sleep ${delay} ms`);
328
+ return await new Promise((res)=>{
329
+ setTimeout(()=>{
330
+ res(true);
331
+ }, delay);
332
+ });
333
+ }
File without changes
@@ -0,0 +1,4 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
File without changes
@@ -0,0 +1,161 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: all[name]
9
+ });
10
+ }
11
+ _export(exports, {
12
+ setRandomStr: ()=>setRandomStr,
13
+ setDefHeaders: ()=>setDefHeaders,
14
+ fetch: ()=>httpFetch,
15
+ get: ()=>requsetGet,
16
+ post: ()=>requestPost
17
+ });
18
+ const _utils = require("@x-drive/utils");
19
+ const _resolveUri = /*#__PURE__*/ _interopRequireDefault(require("./resolve-uri"));
20
+ const _common = require("../common");
21
+ const _nodeFetch = /*#__PURE__*/ _interopRequireDefault(require("node-fetch"));
22
+ function _interopRequireDefault(obj) {
23
+ return obj && obj.__esModule ? obj : {
24
+ default: obj
25
+ };
26
+ }
27
+ const reqLog = log.getLogger("Request");
28
+ /**给指定对象增加一个随机字符串 */ function setRandomStr(query) {
29
+ if ((0, _utils.isObject)(query) && (0, _utils.isUndefined)(query._)) {
30
+ query._ = Date.now().toString(16);
31
+ }
32
+ }
33
+ /**
34
+ * 处理请求地址上的参数
35
+ * @param uri 待处理地址
36
+ * @param params 地址 param 参数
37
+ */ function processParams(uri, params) {
38
+ if ((0, _utils.isObject)(params)) {
39
+ uri = (0, _utils.labelReplace)(uri, params, true, true);
40
+ }
41
+ return uri;
42
+ }
43
+ /**
44
+ * 处理请求上的 search 参数
45
+ * @param uri 待处理地址
46
+ * @param query 参数对象
47
+ */ function processQuery(uri, query) {
48
+ if ((0, _utils.isObject)(query)) {
49
+ uri = (0, _utils.addQuery)(uri, query);
50
+ }
51
+ return uri;
52
+ }
53
+ /**
54
+ * 预处理请求地址
55
+ * @param uri 请求地址
56
+ * @param query 请求参数
57
+ */ function preProcessor(uri, query, random = false) {
58
+ if (random === true) {
59
+ setRandomStr(query);
60
+ }
61
+ return processQuery(processParams(uri, query), query);
62
+ }
63
+ /**默认 Headers */ const DEF_HEADERS = {};
64
+ /**设置默认 Headers */ function setDefHeaders(headers) {
65
+ if ((0, _utils.isObject)(headers)) {
66
+ Object.keys(headers).forEach((key)=>DEF_HEADERS[key] = headers[key]);
67
+ }
68
+ }
69
+ /**获取待发送的请求的 headers */ function getHeaders(headers, uri) {
70
+ headers = (0, _utils.extend)((0, _utils.copy)(DEF_HEADERS), headers || {});
71
+ if ((0, _utils.isString)(uri)) {
72
+ const url = new URL(uri);
73
+ headers.Host = url.host;
74
+ headers.Origin = url.origin;
75
+ }
76
+ return headers;
77
+ }
78
+ const DEF_CONFIG = {
79
+ "type": "json",
80
+ "sameOrigin": false
81
+ };
82
+ /**
83
+ * 获取数据
84
+ * @param type 请求类型
85
+ * @param uri 请求地址
86
+ * @param query 请求参数
87
+ * @param data 发送数据
88
+ * @param config 请求配置
89
+ * @param needProcessConfig 是否需要处理配置
90
+ */ async function httpFetch(type, uri, query, data, config, retry, needProcessConfig = true) {
91
+ if (needProcessConfig) {
92
+ config = (0, _utils.extend)((0, _utils.copy)(DEF_CONFIG), config || {});
93
+ if ((0, _utils.isNumber)(config.retry) && config.retry > 0) {
94
+ retry = config.retry;
95
+ }
96
+ }
97
+ try {
98
+ const method = type.toUpperCase();
99
+ const options = {
100
+ method
101
+ };
102
+ Object.keys(config).forEach((key)=>{
103
+ if (key !== "headers") {
104
+ options[key] = config[key];
105
+ }
106
+ });
107
+ options.headers = getHeaders(config.headers, config.sameOrigin ? uri : null);
108
+ const url = preProcessor((0, _resolveUri.default)(uri), query, config === null || config === void 0 ? void 0 : config.random);
109
+ if (data) {
110
+ options.body = data;
111
+ }
112
+ const resp = await (0, _nodeFetch.default)(url, options);
113
+ if (resp) {
114
+ if ((0, _utils.isExecutable)(config.onResponse)) {
115
+ // @ts-ignore
116
+ await config.onResponse(resp);
117
+ }
118
+ const data1 = await resp[config.type]();
119
+ return data1;
120
+ }
121
+ return null;
122
+ } catch (e) {
123
+ reqLog.error(e);
124
+ if (retry && retry > 0) {
125
+ if ((0, _utils.isNumber)(config.retryDelay) && config.retryDelay > 0) {
126
+ await (0, _common.sleep)(config.retryDelay);
127
+ }
128
+ retry -= 1;
129
+ return await httpFetch(type, uri, query, data, config, retry, false);
130
+ }
131
+ return null;
132
+ }
133
+ }
134
+ /**
135
+ * 发起一个 get 请求
136
+ * @param uri 请求地址
137
+ * @param query 请求参数
138
+ */ async function requsetGet(uri, query, config) {
139
+ uri = preProcessor((0, _resolveUri.default)(uri), query, config === null || config === void 0 ? void 0 : config.random);
140
+ return await httpFetch("get", uri, query, null, config);
141
+ }
142
+ /**
143
+ * 发起一个 post 请求
144
+ * @param uri 请求地址
145
+ * @param query 请求参数
146
+ * @param data 请求数据
147
+ */ async function requestPost(uri, query, data, config) {
148
+ if (query && (0, _utils.isUndefined)(data)) {
149
+ data = query;
150
+ query = {};
151
+ }
152
+ if ((0, _utils.isUndefined)(query)) {
153
+ query = {};
154
+ }
155
+ if ((0, _utils.isUndefined)(data)) {
156
+ data = {};
157
+ }
158
+ uri = (0, _resolveUri.default)(uri);
159
+ uri = preProcessor((0, _resolveUri.default)(uri), query, config === null || config === void 0 ? void 0 : config.random);
160
+ return await httpFetch("post", uri, query, data, config);
161
+ }
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "default", {
6
+ enumerable: true,
7
+ get: ()=>_default
8
+ });
9
+ const _utils = require("@x-drive/utils");
10
+ const internalServers = getSysConfig("internalServers");
11
+ const Apis = getSysConfig("internalApis");
12
+ const ApiMap = new Map();
13
+ Object.keys(Apis).forEach((key)=>{
14
+ let url = Apis[key];
15
+ url = (0, _utils.labelReplace)(url, internalServers, true);
16
+ ApiMap.set(key, url);
17
+ });
18
+ /**
19
+ * 解析请求别名
20
+ * @param uri 请求地址
21
+ */ function resolve(uri) {
22
+ var url = ApiMap.get(uri);
23
+ if (url) {
24
+ return url;
25
+ }
26
+ return uri;
27
+ }
28
+ const _default = resolve;
@@ -53,7 +53,7 @@ function customConfigProcessor(conf, env, envAddConfPath) {
53
53
  if ((0, _common.checkFileStat)(APIS_PATH) && conf.passExtApis !== true) {
54
54
  let apis = [];
55
55
  _fs.default.readdirSync(APIS_PATH).forEach((file)=>{
56
- if (_path.default.extname(file) === ".js") {
56
+ if (!file.startsWith(".") && _path.default.extname(file) === ".js") {
57
57
  apis.push((0, _common.getRealDefaultMod)(require(`${APIS_PATH}/${file}`)));
58
58
  }
59
59
  });
@@ -8,6 +8,7 @@ Object.defineProperty(exports, "default", {
8
8
  });
9
9
  const _common = require("../components/common");
10
10
  const _config = /*#__PURE__*/ _interopRequireDefault(require("../@config/config"));
11
+ const _path = require("path");
11
12
  function _interopRequireDefault(obj) {
12
13
  return obj && obj.__esModule ? obj : {
13
14
  default: obj
@@ -18,12 +19,13 @@ function defConfigProcessor(argv) {
18
19
  // 绑定 IP
19
20
  (_config.default).ip = argv.IP;
20
21
  }
22
+ const apiPath = (0, _path.resolve)("..", "@config", "@apis", "index.js");
21
23
  // api 配置文件处理
22
- var hasCustomApiConf = (0, _common.checkFileStat)("../@config/@apis/index.js", true);
23
- if (hasCustomApiConf) {
24
- _config.default.apis = Object.assign(_config.default.apis || {}, (0, _common.getRealDefaultMod)(require("../conf/@conf/index.js")));
24
+ var hasDefApiConf = (0, _common.checkFileStat)(apiPath, true);
25
+ if (hasDefApiConf) {
26
+ _config.default.apis = Object.assign(_config.default.apis || {}, (0, _common.getRealDefaultMod)(require(apiPath)));
25
27
  }
26
- hasCustomApiConf = null;
28
+ hasDefApiConf = null;
27
29
  return _config.default;
28
30
  }
29
31
  const _default = defConfigProcessor;
@@ -6,18 +6,22 @@ Object.defineProperty(exports, "default", {
6
6
  enumerable: true,
7
7
  get: ()=>_default
8
8
  });
9
+ const serverPackge = require("../../package.json");
9
10
  var info = {};
10
11
  // 业务名称
11
12
  info.mark = getSysConfig("mark") || getSysConfig("name");
12
13
  // 业务版本
13
14
  info.version = getSysConfig("version");
14
15
  // 服务端版本
15
- info.serverVer = require("../../package.json").version;
16
+ info.serverVer = serverPackge.version;
17
+ info.serverName = serverPackge.name;
16
18
  // 业务启动时间
17
19
  // FIX ME : 服务器不是北京时间的时候这个数据跟实际启动的时间存在时差
18
- info.date = requireMod("common").date("Y-m-d h:i:s", Date.now());
20
+ info.date = requireMod("common").date("Y-m-d H:i:s", new Date());
19
21
  // 模块版本信息
20
- const MARK = `${info.mark}@${info.version}&${info.serverVer} (${info.date})`;
22
+ const CLIENT_MARK = `${info.mark}@${info.version}`;
23
+ const SERVER_MARK = `${info.serverName}@${info.serverVer}`;
24
+ const MARK = `${CLIENT_MARK},${SERVER_MARK};Startup@${info.date}`;
21
25
  info = null;
22
26
  /**
23
27
  * 处理函数
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@x-9lab/xlab",
3
- "version": "1.0.0-alpha.3",
3
+ "version": "1.0.2",
4
4
  "description": "9lab 服务端模块",
5
- "versionDesc": "",
5
+ "versionDesc": "修复 type 异常",
6
6
  "scripts": {
7
7
  "dev": "swc src -D ./src/bin --config-file .swcrc -d dist -w",
8
8
  "compile": "swc src -D ./src/bin --config-file .swcrc -d dist",
@@ -20,20 +20,19 @@
20
20
  "@types"
21
21
  ],
22
22
  "dependencies": {
23
- "koa": "2.13.1",
23
+ "koa": "2.13.4",
24
24
  "cron": "1.8.2",
25
- "redis": "4.0.3",
26
- "log4js": "1.1.1",
27
- "liftoff": "3.1.0",
25
+ "log4js": "^1.1.1",
26
+ "liftoff": "4.0.0",
28
27
  "koa-ejs": "4.3.0",
29
- "minimist": "1.2.5",
30
- "request": "2.86.0",
31
- "koa-body": "4.2.0",
32
- "lru-cache": "6.0.0",
28
+ "minimist": "1.2.6",
29
+ "koa-body": "5.0.0",
30
+ "lru-cache": "^6.0.0",
31
+ "node-fetch": "3.0.0",
33
32
  "koa-static": "5.0.0",
34
- "koa-router": "10.0.0",
33
+ "koa-router": "11.0.1",
35
34
  "http-proxy": "1.18.1",
36
- "koa-compress": "5.0.1",
35
+ "koa-compress": "5.1.0",
37
36
  "@x-drive/utils": "1.1.19"
38
37
  },
39
38
  "devDependencies": {
@@ -43,7 +42,6 @@
43
42
  "colors": "1.4.0",
44
43
  "should": "11.2.1",
45
44
  "nodemon": "2.0.12",
46
- "socket.io": "2.0.3",
47
45
  "chokidar": "3.5.3",
48
46
  "typescript": "4.3.4",
49
47
  "@types/node": "16.11.40",
@@ -56,5 +54,9 @@
56
54
  },
57
55
  "bin": {
58
56
  "xlab": "dist/bin/xlab"
57
+ },
58
+ "repository": {
59
+ "type": "git",
60
+ "url": "git+https://github.com/x-9lab/xlab.git"
59
61
  }
60
62
  }
@@ -1,4 +0,0 @@
1
- import type Koa from "koa";
2
- declare function handle(ctx: Koa.Context, next: Koa.Next): Promise<void>;
3
- declare function init(): typeof handle;
4
- export { init };
@@ -1,2 +0,0 @@
1
- declare function handler(): (ctx: import("koa").Context, next: import("koa").Next) => Promise<void>;
2
- export default handler;
@@ -1,170 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- Object.defineProperty(exports, "init", {
6
- enumerable: true,
7
- get: ()=>init
8
- });
9
- const _cache = require("../cache");
10
- const _header = /*#__PURE__*/ _interopRequireWildcard(require("../header"));
11
- const _mime = require("../mime");
12
- const _md5 = require("../md5");
13
- const _path = /*#__PURE__*/ _interopRequireDefault(require("path"));
14
- const _fs = /*#__PURE__*/ _interopRequireDefault(require("fs"));
15
- function _interopRequireDefault(obj) {
16
- return obj && obj.__esModule ? obj : {
17
- default: obj
18
- };
19
- }
20
- function _getRequireWildcardCache(nodeInterop) {
21
- if (typeof WeakMap !== "function") return null;
22
- var cacheBabelInterop = new WeakMap();
23
- var cacheNodeInterop = new WeakMap();
24
- return (_getRequireWildcardCache = function(nodeInterop) {
25
- return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
26
- })(nodeInterop);
27
- }
28
- function _interopRequireWildcard(obj, nodeInterop) {
29
- if (!nodeInterop && obj && obj.__esModule) {
30
- return obj;
31
- }
32
- if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
33
- return {
34
- default: obj
35
- };
36
- }
37
- var cache = _getRequireWildcardCache(nodeInterop);
38
- if (cache && cache.has(obj)) {
39
- return cache.get(obj);
40
- }
41
- var newObj = {};
42
- var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
43
- for(var key in obj){
44
- if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
45
- var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
46
- if (desc && (desc.get || desc.set)) {
47
- Object.defineProperty(newObj, key, desc);
48
- } else {
49
- newObj[key] = obj[key];
50
- }
51
- }
52
- }
53
- newObj.default = obj;
54
- if (cache) {
55
- cache.set(obj, newObj);
56
- }
57
- return newObj;
58
- }
59
- var conf;
60
- // combo 文件缓存时间单位
61
- // 默认一周
62
- // @todo 上 cdn 的话需要根据 cdn 的情况调整这个时间
63
- const COMBO_CACHE_TIME = 1000 * 60 * 60 * 24 * 7;
64
- // combo 组合缓存
65
- const comboCache = (0, _cache.local)("JS_CACHE", {
66
- "maxAge": COMBO_CACHE_TIME,
67
- "max": 200
68
- });
69
- // 单独的文件缓存
70
- // 因为会存在大量公共组件,且有多个入口,当用户从不同的入口进来时会因为组合问题多次调用文件读取
71
- // 增加单独缓存用于减少应用启动初期或 dns 回源时的瞬间压力
72
- const fileCache = (0, _cache.local)("JS_FILE_CACHE", {
73
- "maxAge": COMBO_CACHE_TIME,
74
- "max": 500
75
- });
76
- var logger;
77
- // 扩展名对应的 mime 头
78
- const extMap = {};
79
- Object.keys(_mime.MIME).forEach((ext)=>{
80
- extMap["." + ext] = _mime.MIME[ext];
81
- });
82
- // 处理合并请求,合并请求以两个问号开头
83
- // 请求示例:http://127.0.0.1:5000/??page-manager/1.0.0/page-manager.js,router/1.0.0/router.js,event/1.0.0/event.js,mobile/1.0.0/message/message.js,envi/1.0.0/envi.js,underscore/1.5.2/underscore.js
84
- async function handle(ctx, next) {
85
- let parsedUrl = ctx.url;
86
- let search = ctx.query;
87
- // combo 请求对应的缓存 key
88
- let cacheKey;
89
- // combo 返回内入
90
- let content;
91
- // 如果不是合并请求,则不进行处理,交给下一步
92
- if (!search || parsedUrl.indexOf("??") < 0) {
93
- await next();
94
- return;
95
- }
96
- let filesStr = Object.keys(search)[0].substr(1);
97
- // 设置文件类型,以便正确返回
98
- if (filesStr.indexOf(".js") > -1) {
99
- ctx.set("Content-Type", extMap[".js"]);
100
- } else {
101
- for(let ext in extMap){
102
- if (filesStr.indexOf(ext) > -1) {
103
- ctx.set("Content-Type", extMap[ext]);
104
- break;
105
- }
106
- }
107
- }
108
- // 生成缓存 key
109
- cacheKey = (0, _md5.md5)(filesStr);
110
- // 检查是否有缓存
111
- content = comboCache.get(cacheKey);
112
- // 没有缓存内容,需要读取并且拼接
113
- if (!content) {
114
- // 按照逗号拆分成模块 uri
115
- let uris = filesStr.split(",");
116
- uris = uris.map((uri)=>{
117
- let searchIndex = uri.indexOf("?");
118
- if (searchIndex > -1) {
119
- uri = uri.substring(0, searchIndex);
120
- }
121
- return uri;
122
- });
123
- // 根据 uri 查找文件并拼合
124
- var files = [];
125
- // 读取相关文件
126
- uris.forEach((uri)=>{
127
- // 优先从文件缓存中读
128
- let file = fileCache.get(uri);
129
- if (file) {
130
- files.push(file);
131
- } else {
132
- try {
133
- file = _fs.default.readFileSync(_path.default.resolve(conf.root, "c", uri), "utf8");
134
- } catch (e) {
135
- logger.error("READ COMBO FILE ERROR", uri, e);
136
- }
137
- if (file) {
138
- files.push(file);
139
- fileCache.set(uri, file);
140
- }
141
- }
142
- });
143
- // 合并文件
144
- content = files.join("\n");
145
- // 设置缓存
146
- comboCache.set(cacheKey, content);
147
- } else {
148
- ctx.set("Hit-Combo", cacheKey);
149
- }
150
- // 无法正确读取文件
151
- // 交给后续的 404 处理
152
- if (content === undefined || content === null) {
153
- await next();
154
- return;
155
- }
156
- if (conf.enableComboCache) {
157
- // 生产环境默认开启缓存
158
- // 缓存时间固定为 6 天
159
- _header.cacheControl("6d", ctx);
160
- _header.expire("6d", ctx);
161
- _header.lastModified(null, ctx);
162
- }
163
- // 返回数据
164
- ctx.body = content;
165
- }
166
- function init() {
167
- conf = getSysConfig();
168
- logger = log.getLogger("common");
169
- return handle;
170
- }
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", {
3
- value: true
4
- });
5
- Object.defineProperty(exports, "default", {
6
- enumerable: true,
7
- get: ()=>_default
8
- });
9
- const _combo = require("../components/combo");
10
- function handler() {
11
- return (0, _combo.init)();
12
- }
13
- const _default = handler;