koatty 3.5.7 → 3.5.12-0

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.
Files changed (129) hide show
  1. package/.commitlintrc.js +3 -0
  2. package/.eslintignore +2 -0
  3. package/.huskyrc +5 -0
  4. package/.versionrc.js +16 -0
  5. package/CHANGELOG.md +1 -38
  6. package/README.md +5 -9
  7. package/api-extractor.json +345 -0
  8. package/dist/LICENSE +29 -0
  9. package/dist/README.md +147 -0
  10. package/dist/index.d.ts +363 -19
  11. package/dist/index.js +1266 -26
  12. package/dist/index.mjs +1197 -0
  13. package/dist/package.json +99 -0
  14. package/docs/api/index.md +12 -0
  15. package/docs/api/koatty.apiinput.code.md +11 -0
  16. package/docs/api/koatty.apiinput.data.md +11 -0
  17. package/docs/api/koatty.apiinput.md +22 -0
  18. package/docs/api/koatty.apiinput.message.md +11 -0
  19. package/docs/api/koatty.apioutput.code.md +11 -0
  20. package/docs/api/koatty.apioutput.data.md +11 -0
  21. package/docs/api/koatty.apioutput.md +22 -0
  22. package/docs/api/koatty.apioutput.message.md +11 -0
  23. package/docs/api/koatty.appreadyhookfunc.md +11 -0
  24. package/docs/api/koatty.basecontroller._constructor_.md +20 -0
  25. package/docs/api/koatty.basecontroller._options.md +11 -0
  26. package/docs/api/koatty.basecontroller.app.md +11 -0
  27. package/docs/api/koatty.basecontroller.ctx.md +11 -0
  28. package/docs/api/koatty.basecontroller.fail.md +28 -0
  29. package/docs/api/koatty.basecontroller.init.md +19 -0
  30. package/docs/api/koatty.basecontroller.md +39 -0
  31. package/docs/api/koatty.basecontroller.ok.md +28 -0
  32. package/docs/api/koatty.baseservice._constructor_.md +20 -0
  33. package/docs/api/koatty.baseservice._options.md +11 -0
  34. package/docs/api/koatty.baseservice.app.md +11 -0
  35. package/docs/api/koatty.baseservice.init.md +25 -0
  36. package/docs/api/koatty.baseservice.md +36 -0
  37. package/docs/api/koatty.bindappreadyhook.md +26 -0
  38. package/docs/api/koatty.bootstrap.md +27 -0
  39. package/docs/api/koatty.component.md +27 -0
  40. package/docs/api/koatty.componentscan.md +27 -0
  41. package/docs/api/koatty.configurationscan.md +27 -0
  42. package/docs/api/koatty.controller.md +27 -0
  43. package/docs/api/koatty.httpcontroller.body.md +28 -0
  44. package/docs/api/koatty.httpcontroller.deny.md +26 -0
  45. package/docs/api/koatty.httpcontroller.expires.md +26 -0
  46. package/docs/api/koatty.httpcontroller.fail.md +28 -0
  47. package/docs/api/koatty.httpcontroller.header.md +27 -0
  48. package/docs/api/koatty.httpcontroller.isget.md +19 -0
  49. package/docs/api/koatty.httpcontroller.ismethod.md +26 -0
  50. package/docs/api/koatty.httpcontroller.ispost.md +19 -0
  51. package/docs/api/koatty.httpcontroller.json.md +26 -0
  52. package/docs/api/koatty.httpcontroller.md +35 -0
  53. package/docs/api/koatty.httpcontroller.ok.md +28 -0
  54. package/docs/api/koatty.httpcontroller.param.md +26 -0
  55. package/docs/api/koatty.httpcontroller.redirect.md +27 -0
  56. package/docs/api/koatty.httpcontroller.type.md +27 -0
  57. package/docs/api/koatty.icontroller.__after.md +11 -0
  58. package/docs/api/koatty.icontroller.__befor.md +11 -0
  59. package/docs/api/koatty.icontroller.app.md +11 -0
  60. package/docs/api/koatty.icontroller.ctx.md +11 -0
  61. package/docs/api/koatty.icontroller.fail.md +11 -0
  62. package/docs/api/koatty.icontroller.md +25 -0
  63. package/docs/api/koatty.icontroller.ok.md +11 -0
  64. package/docs/api/koatty.imiddleware.md +20 -0
  65. package/docs/api/koatty.imiddleware.run.md +11 -0
  66. package/docs/api/koatty.iplugin.md +20 -0
  67. package/docs/api/koatty.iplugin.run.md +11 -0
  68. package/docs/api/koatty.iservice.app.md +11 -0
  69. package/docs/api/koatty.iservice.md +20 -0
  70. package/docs/api/koatty.logger.md +11 -0
  71. package/docs/api/koatty.md +51 -0
  72. package/docs/api/koatty.middleware.md +27 -0
  73. package/docs/api/koatty.plugin.md +27 -0
  74. package/docs/api/koatty.service.md +27 -0
  75. package/jest.config.js +0 -2
  76. package/jest_html_reporters.html +1 -1
  77. package/package.json +40 -39
  78. package/rollup.config.js +63 -0
  79. package/scripts/copyright.js +28 -0
  80. package/scripts/postBuild.js +10 -0
  81. package/tsconfig.json +4 -2
  82. package/babel.config.js +0 -21
  83. package/commitlint.config.js +0 -14
  84. package/dist/config/config.d.ts +0 -21
  85. package/dist/config/config.js +0 -25
  86. package/dist/config/config.js.map +0 -1
  87. package/dist/config/middleware.d.ts +0 -23
  88. package/dist/config/middleware.js +0 -34
  89. package/dist/config/middleware.js.map +0 -1
  90. package/dist/config/plugin.d.ts +0 -11
  91. package/dist/config/plugin.js +0 -15
  92. package/dist/config/plugin.js.map +0 -1
  93. package/dist/config/router.d.ts +0 -8
  94. package/dist/config/router.js +0 -32
  95. package/dist/config/router.js.map +0 -1
  96. package/dist/controller/BaseController.d.ts +0 -60
  97. package/dist/controller/BaseController.js +0 -137
  98. package/dist/controller/BaseController.js.map +0 -1
  99. package/dist/controller/HttpController.d.ts +0 -131
  100. package/dist/controller/HttpController.js +0 -215
  101. package/dist/controller/HttpController.js.map +0 -1
  102. package/dist/core/Bootstrap.d.ts +0 -50
  103. package/dist/core/Bootstrap.js +0 -217
  104. package/dist/core/Bootstrap.js.map +0 -1
  105. package/dist/core/Component.d.ts +0 -94
  106. package/dist/core/Component.js +0 -89
  107. package/dist/core/Component.js.map +0 -1
  108. package/dist/core/Constants.d.ts +0 -11
  109. package/dist/core/Constants.js +0 -24
  110. package/dist/core/Constants.js.map +0 -1
  111. package/dist/core/Loader.d.ts +0 -110
  112. package/dist/core/Loader.js +0 -407
  113. package/dist/core/Loader.js.map +0 -1
  114. package/dist/index.js.map +0 -1
  115. package/dist/middleware/PayloadMiddleware.d.ts +0 -11
  116. package/dist/middleware/PayloadMiddleware.js +0 -22
  117. package/dist/middleware/PayloadMiddleware.js.map +0 -1
  118. package/dist/middleware/TraceMiddleware.d.ts +0 -11
  119. package/dist/middleware/TraceMiddleware.js +0 -22
  120. package/dist/middleware/TraceMiddleware.js.map +0 -1
  121. package/dist/service/BaseService.d.ts +0 -33
  122. package/dist/service/BaseService.js +0 -32
  123. package/dist/service/BaseService.js.map +0 -1
  124. package/dist/util/Helper.d.ts +0 -25
  125. package/dist/util/Helper.js +0 -117
  126. package/dist/util/Helper.js.map +0 -1
  127. package/dist/util/Logger.d.ts +0 -27
  128. package/dist/util/Logger.js +0 -41
  129. package/dist/util/Logger.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,26 +1,1266 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Logger = exports.Helper = void 0;
4
- const tslib_1 = require("tslib");
5
- /**
6
- * @ author: richen
7
- * @ copyright: Copyright (c) - <richenlin(at)gmail.com>
8
- * @ license: BSD (3-Clause)
9
- * @ version: 2020-05-18 10:43:05
10
- */
11
- (0, tslib_1.__exportStar)(require("./controller/BaseController"), exports);
12
- (0, tslib_1.__exportStar)(require("./controller/HttpController"), exports);
13
- (0, tslib_1.__exportStar)(require("./core/Bootstrap"), exports);
14
- (0, tslib_1.__exportStar)(require("./core/Component"), exports);
15
- (0, tslib_1.__exportStar)(require("./service/BaseService"), exports);
16
- (0, tslib_1.__exportStar)(require("koatty_core"), exports);
17
- (0, tslib_1.__exportStar)(require("koatty_container"), exports);
18
- (0, tslib_1.__exportStar)(require("koatty_exception"), exports);
19
- (0, tslib_1.__exportStar)(require("koatty_router"), exports);
20
- (0, tslib_1.__exportStar)(require("koatty_serve"), exports);
21
- (0, tslib_1.__exportStar)(require("koatty_trace"), exports);
22
- var Helper_1 = require("./util/Helper");
23
- Object.defineProperty(exports, "Helper", { enumerable: true, get: function () { return Helper_1.Helper; } });
24
- var Logger_1 = require("./util/Logger");
25
- Object.defineProperty(exports, "Logger", { enumerable: true, get: function () { return Logger_1.Logger; } });
26
- //# sourceMappingURL=index.js.map
1
+ /*!
2
+ * @Author: richen
3
+ * @Date: 2021-12-21 12:21:50
4
+ * @License: BSD (3-Clause)
5
+ * @Copyright (c) - <richenlin(at)gmail.com>
6
+ * @HomePage: https://koatty.org/
7
+ */
8
+ 'use strict';
9
+
10
+ Object.defineProperty(exports, '__esModule', { value: true });
11
+
12
+ var koatty_lib = require('koatty_lib');
13
+ require('reflect-metadata');
14
+ var koatty_router = require('koatty_router');
15
+ var koatty_core = require('koatty_core');
16
+ var koatty_serve = require('koatty_serve');
17
+ var koatty_container = require('koatty_container');
18
+ var path = require('path');
19
+ var koatty_loader = require('koatty_loader');
20
+ var koatty_config = require('koatty_config');
21
+ var koatty_logger = require('koatty_logger');
22
+ var koatty_exception = require('koatty_exception');
23
+ var koatty_trace = require('koatty_trace');
24
+ var koatty_payload = require('koatty_payload');
25
+
26
+ function _interopNamespace(e) {
27
+ if (e && e.__esModule) return e;
28
+ var n = Object.create(null);
29
+ if (e) {
30
+ Object.keys(e).forEach(function (k) {
31
+ if (k !== 'default') {
32
+ var d = Object.getOwnPropertyDescriptor(e, k);
33
+ Object.defineProperty(n, k, d.get ? d : {
34
+ enumerable: true,
35
+ get: function () { return e[k]; }
36
+ });
37
+ }
38
+ });
39
+ }
40
+ n["default"] = e;
41
+ return Object.freeze(n);
42
+ }
43
+
44
+ var path__namespace = /*#__PURE__*/_interopNamespace(path);
45
+
46
+ /**
47
+ * @ author: richen
48
+ * @ copyright: Copyright (c) - <richenlin(at)gmail.com>
49
+ * @ license: BSD (3-Clause)
50
+ * @ version: 2020-05-10 11:49:15
51
+ */
52
+ /**
53
+ * Check class file
54
+ * name should be always the same as class name
55
+ * class must be unique
56
+ *
57
+ * @export
58
+ * @param {string} fileName
59
+ * @param {string} xpath
60
+ * @param {*} target
61
+ * @param {Set<unknown>} [exSet]
62
+ * @returns {*}
63
+ */
64
+ function checkClass(fileName, xpath, target, exSet) {
65
+ if (koatty_lib.Helper.isClass(target) && target.name != fileName) { // export default class name{}
66
+ throw Error(`The file(${xpath}) name should be always the same as class name.`);
67
+ }
68
+ if (target["__esModule"]) {
69
+ if (target.name === undefined) { // export class name{}
70
+ const keys = Object.keys(target);
71
+ if (keys[0] != fileName && koatty_lib.Helper.isClass(target[keys[0]])) {
72
+ throw Error(`The file(${xpath}) name should be always the same as class name.`);
73
+ }
74
+ }
75
+ else if (target.name != fileName) { // export default class {}
76
+ throw Error(`The file(${xpath}) name should be always the same as class name.`);
77
+ }
78
+ }
79
+ if (!exSet) {
80
+ return;
81
+ }
82
+ if (exSet.has(fileName)) {
83
+ throw new Error(`A same class already exists. at \`${xpath}\`.`);
84
+ }
85
+ exSet.add(fileName);
86
+ return;
87
+ }
88
+ /**
89
+ * Format api interface data format
90
+ *
91
+ * @private
92
+ * @param {Error | string | ApiInput} msg 待处理的接口数据信息|接口msg
93
+ * @param {*} data 待返回的数据
94
+ * @param {number} defaultCode 默认错误码
95
+ * @returns {ApiOutput} 格式化之后的接口数据
96
+ * @memberof BaseController
97
+ */
98
+ function formatApiData(msg, data, defaultCode) {
99
+ let obj = {
100
+ code: defaultCode,
101
+ message: '',
102
+ data: null,
103
+ };
104
+ if (koatty_lib.Helper.isError(msg)) {
105
+ const { code, message } = msg;
106
+ obj.code = code || defaultCode;
107
+ obj.message = message;
108
+ }
109
+ else if (koatty_lib.Helper.isObject(msg)) {
110
+ obj = { ...obj, ...msg };
111
+ }
112
+ else {
113
+ obj.message = msg;
114
+ obj.data = data;
115
+ }
116
+ return obj;
117
+ }
118
+
119
+ /**
120
+ * @ author: richen
121
+ * @ copyright: Copyright (c) - <richenlin(at)gmail.com>
122
+ * @ license: BSD (3-Clause)
123
+ * @ version: 2020-05-20 15:45:24
124
+ */
125
+ /**
126
+ * Base controller
127
+ *
128
+ * @export
129
+ * @class BaseController
130
+ * @implements {IController}
131
+ */
132
+ class BaseController {
133
+ /**
134
+ * instance of BaseController.
135
+ * @param {Koatty} app
136
+ * @param {KoattyContext} ctx
137
+ * @memberof BaseController
138
+ */
139
+ constructor(ctx) {
140
+ this.ctx = ctx;
141
+ this.init();
142
+ }
143
+ /**
144
+ * init
145
+ *
146
+ * @protected
147
+ * @memberof BaseController
148
+ */
149
+ init() {
150
+ }
151
+ // /**
152
+ // * Class pre-execution method, executed before each class member methods (except constructor, init, __after) are executed.
153
+ // *
154
+ // * @returns {Promise<any>}
155
+ // * @memberof BaseController
156
+ // */
157
+ // public __before(): Promise<any> {
158
+ // return Promise.resolve();
159
+ // }
160
+ // /**
161
+ // * Class after-execution method,after each class member methods (except constructor, init, __before) are executed.
162
+ // *
163
+ // * @public
164
+ // * @returns {*}
165
+ // * @memberof BaseController
166
+ // */
167
+ // public __after(): Promise<any> {
168
+ // return Promise.resolve();
169
+ // }
170
+ /**
171
+ * Response to normalize json format content for success
172
+ *
173
+ * @param {(string | ApiInput)} msg 待处理的message消息
174
+ * @param {*} [data] 待处理的数据
175
+ * @param {number} [code=200] 错误码,默认0
176
+ * @returns {*}
177
+ * @memberof BaseController
178
+ */
179
+ ok(msg, data, code = 0) {
180
+ const obj = formatApiData(msg, data, code);
181
+ return Promise.resolve(obj);
182
+ }
183
+ /**
184
+ * Response to normalize json format content for fail
185
+ *
186
+ * @param {(string | ApiInput)} msg
187
+ * @param {*} [data]
188
+ * @param {number} [code=1]
189
+ * @returns {*}
190
+ * @memberof BaseController
191
+ */
192
+ fail(msg, data, code = 1) {
193
+ const obj = formatApiData(msg, data, code);
194
+ return Promise.resolve(obj);
195
+ }
196
+ }
197
+ // const properties = ["constructor", "init"];
198
+ // export const BaseController = new Proxy(Base, {
199
+ // set(target, key, value, receiver) {
200
+ // if (Reflect.get(target, key, receiver) === undefined) {
201
+ // return Reflect.set(target, key, value, receiver);
202
+ // } else if (key === "init") {
203
+ // return Reflect.set(target, key, value, receiver);
204
+ // } else {
205
+ // throw Error("Cannot redefine getter-only property");
206
+ // }
207
+ // },
208
+ // deleteProperty(target, key) {
209
+ // throw Error("Cannot delete getter-only property");
210
+ // },
211
+ // construct(target, args, newTarget) {
212
+ // Reflect.ownKeys(target.prototype).map((n) => {
213
+ // if (newTarget.prototype.hasOwnProperty(n) && !properties.includes(Helper.toString(n))) {
214
+ // throw Error(`Cannot override the final method "${Helper.toString(n)}"`);
215
+ // }
216
+ // });
217
+ // return Reflect.construct(target, args, newTarget);
218
+ // }
219
+ // });
220
+
221
+ /**
222
+ * @ author: richen
223
+ * @ copyright: Copyright (c) - <richenlin(at)gmail.com>
224
+ * @ license: BSD (3-Clause)
225
+ * @ version: 2020-05-20 15:45:24
226
+ */
227
+ /**
228
+ * HTTP controller
229
+ *
230
+ * @export
231
+ * @class HttpController
232
+ * @implements {IController}
233
+ */
234
+ class HttpController extends BaseController {
235
+ /**
236
+ * Whether it is a GET request
237
+ *
238
+ * @public
239
+ * @returns {boolean}
240
+ * @memberof HttpController
241
+ */
242
+ isGet() {
243
+ return this.ctx.method === "GET";
244
+ }
245
+ /**
246
+ * Whether it is a POST request
247
+ *
248
+ * @public
249
+ * @returns {boolean}
250
+ * @memberof HttpController
251
+ */
252
+ isPost() {
253
+ return this.ctx.method === "POST";
254
+ }
255
+ /**
256
+ * Determines whether the METHOD request is specified
257
+ *
258
+ * @public
259
+ * @param {string} method
260
+ * @returns {boolean}
261
+ * @memberof HttpController
262
+ */
263
+ isMethod(method) {
264
+ return this.ctx.method === method.toUpperCase();
265
+ }
266
+ /**
267
+ * Get/Set headers.
268
+ *
269
+ * @public
270
+ * @param {string} [name]
271
+ * @param {*} [value]
272
+ * @returns {*}
273
+ * @memberof HttpController
274
+ */
275
+ header(name, value) {
276
+ if (name === undefined) {
277
+ return this.ctx.headers;
278
+ }
279
+ if (value === undefined) {
280
+ return this.ctx.get(name);
281
+ }
282
+ return this.ctx.set(name, value);
283
+ }
284
+ /**
285
+ * Get POST/GET parameters, the POST value is priority.
286
+ *
287
+ * @param {string} [name]
288
+ * @returns
289
+ * @memberof HttpController
290
+ */
291
+ param(name) {
292
+ return this.ctx.bodyParser().then((body) => {
293
+ const getParams = this.ctx.queryParser() || {};
294
+ const postParams = (body.post ? body.post : body) || {};
295
+ if (name !== undefined) {
296
+ return postParams[name] === undefined ? getParams[name] : postParams[name];
297
+ }
298
+ return { ...getParams, ...postParams };
299
+ });
300
+ }
301
+ /**
302
+ * Set response content-type
303
+ *
304
+ * @public
305
+ * @param {string} contentType
306
+ * @param {(string | boolean)} [encoding]
307
+ * @returns {string}
308
+ * @memberof HttpController
309
+ */
310
+ type(contentType, encoding) {
311
+ if (encoding !== false && !contentType.includes("charset")) {
312
+ contentType = `${contentType}; charset=${encoding || this.app.config("encoding")}`;
313
+ }
314
+ this.ctx.type = contentType;
315
+ return contentType;
316
+ }
317
+ /**
318
+ * set cache-control and expires header
319
+ *
320
+ * @public
321
+ * @param {number} [timeout=30]
322
+ * @returns {void}
323
+ * @memberof HttpController
324
+ */
325
+ expires(timeout = 30) {
326
+ timeout = koatty_lib.Helper.toNumber(timeout) * 1000;
327
+ const date = new Date(Date.now() + timeout);
328
+ this.ctx.set("Cache-Control", `max-age=${timeout}`);
329
+ return this.ctx.set("Expires", date.toUTCString());
330
+ }
331
+ /**
332
+ * Url redirect
333
+ *
334
+ * @param {string} urls
335
+ * @param {string} [alt]
336
+ * @returns {void}
337
+ * @memberof HttpController
338
+ */
339
+ redirect(urls, alt) {
340
+ return this.ctx.redirect(urls, alt);
341
+ }
342
+ /**
343
+ * Block access
344
+ *
345
+ * @param {number} [code=403]
346
+ * @returns {Promise<any>}
347
+ * @memberof HttpController
348
+ */
349
+ deny(code = 403) {
350
+ return this.ctx.throw(code);
351
+ }
352
+ /**
353
+ * Set response Body content
354
+ *
355
+ * @param {*} data
356
+ * @param {string} [contentType]
357
+ * @param {string} [encoding]
358
+ * @returns {Promise<any>}
359
+ * @memberof HttpController
360
+ */
361
+ body(data, contentType, encoding) {
362
+ contentType = contentType || "text/plain";
363
+ encoding = encoding || this.app.config("encoding") || "utf-8";
364
+ this.type(contentType, encoding);
365
+ this.ctx.body = data;
366
+ return null;
367
+ }
368
+ /**
369
+ * Respond to json formatted content
370
+ *
371
+ * @param {*} data
372
+ * @returns {Promise<any>}
373
+ * @memberof HttpController
374
+ */
375
+ json(data) {
376
+ return this.body(data, "application/json");
377
+ }
378
+ /**
379
+ * Response to normalize json format content for success
380
+ *
381
+ * @param {(string | ApiInput)} msg 待处理的message消息
382
+ * @param {*} [data] 待处理的数据
383
+ * @param {number} [code=200] 错误码,默认0
384
+ * @returns {*}
385
+ * @memberof HttpController
386
+ */
387
+ ok(msg, data, code = 0) {
388
+ const obj = formatApiData(msg, data, code);
389
+ return this.json(obj);
390
+ }
391
+ /**
392
+ * Response to normalize json format content for fail
393
+ *
394
+ * @param {(string | ApiInput)} msg
395
+ * @param {*} [data]
396
+ * @param {number} [code=1]
397
+ * @returns {*}
398
+ * @memberof HttpController
399
+ */
400
+ fail(msg, data, code = 1) {
401
+ const obj = formatApiData(msg, data, code);
402
+ return this.json(obj);
403
+ }
404
+ }
405
+ // const properties = ["constructor", "init"];
406
+ // export const HttpController = new Proxy(Base, {
407
+ // set(target, key, value, receiver) {
408
+ // if (Reflect.get(target, key, receiver) === undefined) {
409
+ // return Reflect.set(target, key, value, receiver);
410
+ // } else if (key === "init") {
411
+ // return Reflect.set(target, key, value, receiver);
412
+ // } else {
413
+ // throw Error("Cannot redefine getter-only property");
414
+ // }
415
+ // },
416
+ // deleteProperty(target, key) {
417
+ // throw Error("Cannot delete getter-only property");
418
+ // },
419
+ // construct(target, args, newTarget) {
420
+ // Reflect.ownKeys(target.prototype).map((n) => {
421
+ // if (newTarget.prototype.hasOwnProperty(n) && !properties.includes(Helper.toString(n))) {
422
+ // throw Error(`Cannot override the final method "${Helper.toString(n)}"`);
423
+ // }
424
+ // });
425
+ // return Reflect.construct(target, args, newTarget);
426
+ // }
427
+ // });
428
+
429
+ /**
430
+ * @ author: richen
431
+ * @ copyright: Copyright (c) - <richenlin(at)gmail.com>
432
+ * @ license: BSD (3-Clause)
433
+ * @ version: 2020-05-10 11:49:15
434
+ */
435
+ // Logger
436
+ const Logger = koatty_logger.DefaultLogger;
437
+ /**
438
+ * SetLogger
439
+ *
440
+ * @export
441
+ * @param {{
442
+ * logLevel?: LogLevelType;
443
+ * logConsole?: boolean;
444
+ * logFile?: boolean;
445
+ * logFileLevel?: LogLevelType;
446
+ * logFilePath?: string;
447
+ * }} config
448
+ */
449
+ function SetLogger(config) {
450
+ if (config.logLevel !== undefined) {
451
+ koatty_logger.DefaultLogger.setLevel(config.logLevel);
452
+ }
453
+ if (config.logConsole !== undefined) {
454
+ koatty_logger.DefaultLogger.setLogConsole(config.logConsole);
455
+ }
456
+ if (config.logFile !== undefined) {
457
+ koatty_logger.DefaultLogger.setLogFile(config.logFile);
458
+ koatty_logger.DefaultLogger.setLogFilePath(config.logFilePath);
459
+ }
460
+ if (config.logFileLevel !== undefined) {
461
+ koatty_logger.DefaultLogger.setLogFileLevel(config.logFileLevel);
462
+ }
463
+ }
464
+
465
+ /**
466
+ * Base class
467
+ *
468
+ * @export
469
+ * @class Base
470
+ */
471
+ class BaseService {
472
+ /**
473
+ * instance of Base.
474
+ * @param {...any[]} arg
475
+ * @memberof Base
476
+ */
477
+ constructor(...arg) {
478
+ this.init(arg);
479
+ }
480
+ /**
481
+ * init
482
+ *
483
+ * @protected
484
+ * @param {...any[]} arg
485
+ * @memberof Base
486
+ */
487
+ init(...arg) {
488
+ // todo
489
+ // Logger.Debug(arg)
490
+ }
491
+ }
492
+
493
+ /**
494
+ * @ author: richen
495
+ * @ copyright: Copyright (c) - <richenlin(at)gmail.com>
496
+ * @ license: BSD (3-Clause)
497
+ * @ version: 2020-05-10 11:49:15
498
+ */
499
+ const COMPONENT_SCAN = 'COMPONENT_SCAN';
500
+ const CONFIGURATION_SCAN = 'CONFIGURATION_SCAN';
501
+ const APP_READY_HOOK = "APP_READY_HOOK";
502
+ // tslint:disable: no-irregular-whitespace
503
+ const LOGO = `
504
+
505
+ ██  ██  ██████  █████  ████████ ████████ ██  ██ 
506
+ ██  ██  ██    ██ ██   ██    ██       ██     ██  ██  
507
+ █████   ██  ██ ███████  ██  ██   ████  
508
+ ██  ██  ██  ██ ██   ██  ██  ██   ██  
509
+ ██  ██  ██████  ██  ██  ██  ██  ██ 
510
+ https://github.com/koatty
511
+ `;
512
+
513
+ class TraceMiddleware {
514
+ run(options, app) {
515
+ return koatty_trace.Trace(options, app);
516
+ }
517
+ }
518
+
519
+ class PayloadMiddleware {
520
+ run(options, app) {
521
+ return koatty_payload.Payload(options, app);
522
+ }
523
+ }
524
+
525
+ /**
526
+ * @ author: richen
527
+ * @ copyright: Copyright (c) - <richenlin(at)gmail.com>
528
+ * @ license: BSD (3-Clause)
529
+ * @ version: 2020-07-06 11:18:01
530
+ */
531
+ /**
532
+ *
533
+ */
534
+ class Loader {
535
+ /**
536
+ * initialize env
537
+ *
538
+ * @static
539
+ * @param {Koatty} app
540
+ * @memberof Loader
541
+ */
542
+ static initialize(app) {
543
+ var _a, _b;
544
+ const env = ((_a = process.execArgv) !== null && _a !== void 0 ? _a : []).join(",");
545
+ if (env.indexOf('ts-node') > -1 || env.indexOf('--debug') > -1) {
546
+ app.appDebug = true;
547
+ }
548
+ // app.env
549
+ app.env = process.env.KOATTY_ENV || process.env.NODE_ENV;
550
+ if ((env.indexOf('--production') > -1) || (((_b = app.env) !== null && _b !== void 0 ? _b : '').indexOf('pro') > -1)) {
551
+ app.appDebug = false;
552
+ }
553
+ if (app.appDebug) {
554
+ app.env = 'development';
555
+ process.env.NODE_ENV = 'development';
556
+ process.env.APP_DEBUG = 'true';
557
+ Logger.setLevel("DEBUG");
558
+ }
559
+ else {
560
+ app.env = 'production';
561
+ process.env.NODE_ENV = 'production';
562
+ Logger.setLevel("INFO");
563
+ }
564
+ // define path
565
+ const rootPath = app.rootPath || process.cwd();
566
+ const appPath = app.appPath || path__namespace.resolve(rootPath, env.indexOf('ts-node') > -1 ? 'src' : 'dist');
567
+ const thinkPath = path__namespace.resolve(__dirname, '..');
568
+ koatty_lib.Helper.define(app, 'rootPath', rootPath);
569
+ koatty_lib.Helper.define(app, 'appPath', appPath);
570
+ koatty_lib.Helper.define(app, 'thinkPath', thinkPath);
571
+ process.env.ROOT_PATH = rootPath;
572
+ process.env.APP_PATH = appPath;
573
+ process.env.THINK_PATH = thinkPath;
574
+ // Compatible with old version, will be deprecated
575
+ koatty_lib.Helper.define(app, 'prevent', koatty_exception.prevent);
576
+ koatty_lib.Helper.define(app, 'root_path', rootPath);
577
+ koatty_lib.Helper.define(app, 'app_path', appPath);
578
+ koatty_lib.Helper.define(app, 'think_path', thinkPath);
579
+ }
580
+ /**
581
+ * Get component metadata
582
+ *
583
+ * @static
584
+ * @param {Koatty} app
585
+ * @param {*} target
586
+ * @returns {*} {any[]}
587
+ * @memberof Loader
588
+ */
589
+ static GetComponentMetas(app, target) {
590
+ let componentMetas = [];
591
+ const componentMeta = koatty_container.IOCContainer.getClassMetadata(koatty_container.TAGGED_CLS, COMPONENT_SCAN, target);
592
+ if (componentMeta) {
593
+ if (koatty_lib.Helper.isArray(componentMeta)) {
594
+ componentMetas = componentMeta;
595
+ }
596
+ else {
597
+ componentMetas.push(componentMeta);
598
+ }
599
+ }
600
+ if (componentMetas.length < 1) {
601
+ componentMetas = [app.appPath];
602
+ }
603
+ return componentMetas;
604
+ }
605
+ /**
606
+ * Load all bean, excepted config/*、App.ts
607
+ *
608
+ * @static
609
+ * @param {Koatty} app
610
+ * @param {*} target
611
+ * @memberof Loader
612
+ */
613
+ static CheckAllComponents(app, target) {
614
+ // component metadata
615
+ const componentMetas = Loader.GetComponentMetas(app, target);
616
+ // configuration metadata
617
+ const configurationMetas = Loader.GetConfigurationMetas(app, target);
618
+ const exSet = new Set();
619
+ koatty_loader.Load(componentMetas, '', (fileName, xpath, xTarget) => {
620
+ checkClass(fileName, xpath, xTarget, exSet);
621
+ }, ['**/**.js', '**/**.ts', '!**/**.d.ts'], [...configurationMetas, `${target.name || '.no'}.ts`]);
622
+ exSet.clear();
623
+ }
624
+ /**
625
+ * Get configuration metadata
626
+ *
627
+ * @static
628
+ * @param {Koatty} app
629
+ * @param {*} target
630
+ * @returns {*} {any[]}
631
+ * @memberof Loader
632
+ */
633
+ static GetConfigurationMetas(app, target) {
634
+ const confMeta = koatty_container.IOCContainer.getClassMetadata(koatty_container.TAGGED_CLS, CONFIGURATION_SCAN, target);
635
+ let configurationMetas = [];
636
+ if (confMeta) {
637
+ if (koatty_lib.Helper.isArray(confMeta)) {
638
+ configurationMetas = confMeta;
639
+ }
640
+ else {
641
+ configurationMetas.push(confMeta);
642
+ }
643
+ }
644
+ return configurationMetas;
645
+ }
646
+ /**
647
+ * Set Logger level
648
+ *
649
+ * @static
650
+ * @param {Koatty} app
651
+ * @memberof Loader
652
+ */
653
+ static SetLogger(app) {
654
+ var _a;
655
+ const configs = (_a = app.getMetaData("_configs")) !== null && _a !== void 0 ? _a : {};
656
+ //Logger
657
+ if (configs.config) {
658
+ const opt = configs.config;
659
+ let logLevel = "DEBUG", logFileLevel = "INFO", logConsole = true, logFile = false, logFilePath = app.rootPath + "/logs";
660
+ if (app.env === "production") {
661
+ logLevel = "INFO";
662
+ logFileLevel = "WARN";
663
+ logConsole = false;
664
+ logFile = true;
665
+ }
666
+ if (opt.logs_level) {
667
+ logLevel = opt.logs_level;
668
+ }
669
+ if (opt.logs_write_level) {
670
+ logFileLevel = opt.logs_write_level;
671
+ }
672
+ if (opt.logs_write !== undefined) {
673
+ logFile = !!opt.logs_write;
674
+ }
675
+ if (opt.logs_console !== undefined) {
676
+ logConsole = !!opt.logs_console;
677
+ }
678
+ if (opt.logs_path) {
679
+ logFilePath = opt.logs_path;
680
+ }
681
+ SetLogger({ logLevel, logConsole, logFile, logFileLevel, logFilePath });
682
+ }
683
+ }
684
+ /**
685
+ * Load app ready hook funcs
686
+ *
687
+ * @static
688
+ * @param {Koatty} app
689
+ * @param {*} target
690
+ * @memberof Loader
691
+ */
692
+ static LoadAppReadyHooks(app, target) {
693
+ const funcs = koatty_container.IOCContainer.getClassMetadata(koatty_container.TAGGED_CLS, APP_READY_HOOK, target);
694
+ if (koatty_lib.Helper.isArray(funcs)) {
695
+ funcs.forEach((element) => {
696
+ app.once('appReady', () => element(app));
697
+ return null;
698
+ });
699
+ }
700
+ }
701
+ /**
702
+ * Load configuration
703
+ *
704
+ * @static
705
+ * @param {Koatty} app
706
+ * @param {string[]} [loadPath]
707
+ * @memberof Loader
708
+ */
709
+ static LoadConfigs(app, loadPath) {
710
+ const frameConfig = {};
711
+ // Logger.Debug(`Load configuration path: ${app.thinkPath}/config`);
712
+ koatty_loader.Load(["./config"], app.thinkPath, function (name, path, exp) {
713
+ frameConfig[name] = exp;
714
+ });
715
+ if (koatty_lib.Helper.isArray(loadPath)) {
716
+ loadPath = loadPath.length > 0 ? loadPath : ["./config"];
717
+ }
718
+ let appConfig = koatty_config.LoadConfigs(loadPath, app.appPath);
719
+ appConfig = koatty_lib.Helper.extend(frameConfig, appConfig, true);
720
+ app.setMetaData("_configs", appConfig);
721
+ }
722
+ /**
723
+ * Load middlewares
724
+ * [async]
725
+ * @static
726
+ * @param {*} app
727
+ * @param {(string | string[])} [loadPath]
728
+ * @memberof Loader
729
+ */
730
+ static async LoadMiddlewares(app, loadPath) {
731
+ var _a, _b;
732
+ let middlewareConf = app.config(undefined, "middleware");
733
+ if (koatty_lib.Helper.isEmpty(middlewareConf)) {
734
+ middlewareConf = { config: {}, list: [] };
735
+ }
736
+ //Mount default middleware
737
+ koatty_loader.Load(loadPath || ["./middleware"], app.thinkPath);
738
+ //Mount application middleware
739
+ // const middleware: any = {};
740
+ const appMiddleware = (_a = koatty_container.IOCContainer.listClass("MIDDLEWARE")) !== null && _a !== void 0 ? _a : [];
741
+ appMiddleware.push({ id: "TraceMiddleware", target: TraceMiddleware });
742
+ appMiddleware.push({ id: "PayloadMiddleware", target: PayloadMiddleware });
743
+ appMiddleware.forEach((item) => {
744
+ var _a;
745
+ item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("MIDDLEWARE:", "");
746
+ if (item.id && koatty_lib.Helper.isClass(item.target)) {
747
+ koatty_container.IOCContainer.reg(item.id, item.target, { scope: "Prototype", type: "MIDDLEWARE", args: [] });
748
+ // middleware[item.id] = item.target;
749
+ }
750
+ });
751
+ const middlewareConfList = middlewareConf.list;
752
+ const defaultList = ["TraceMiddleware", "PayloadMiddleware"];
753
+ middlewareConfList.forEach((item) => {
754
+ if (!defaultList.includes(item)) {
755
+ defaultList.push(item);
756
+ }
757
+ });
758
+ // if (defaultList.length > middlewareConfList.length) {
759
+ // Logger.Warn("Some middleware is loaded but not allowed to execute.");
760
+ // }
761
+ //de-duplication
762
+ const appMList = [...new Set(defaultList)];
763
+ //Automatically call middleware
764
+ for (const key of appMList) {
765
+ const handle = koatty_container.IOCContainer.get(key, "MIDDLEWARE");
766
+ if (!handle) {
767
+ Logger.Error(`Middleware ${key} load error.`);
768
+ continue;
769
+ }
770
+ if (!koatty_lib.Helper.isFunction(handle.run)) {
771
+ Logger.Error(`Middleware ${key} must be implements method 'run'.`);
772
+ continue;
773
+ }
774
+ if (middlewareConf.config[key] === false) {
775
+ Logger.Warn(`Middleware ${key} is loaded but not allowed to execute.`);
776
+ continue;
777
+ }
778
+ Logger.Debug(`Load middleware: ${key}`);
779
+ const result = await handle.run((_b = middlewareConf.config[key]) !== null && _b !== void 0 ? _b : {}, app);
780
+ if (koatty_lib.Helper.isFunction(result)) {
781
+ if (result.length < 3) {
782
+ app.use(result);
783
+ }
784
+ else {
785
+ app.useExp(result);
786
+ }
787
+ }
788
+ }
789
+ // app.setMetaData("_middlewares", middleware);
790
+ }
791
+ /**
792
+ * Load controllers
793
+ *
794
+ * @static
795
+ * @param {*} app
796
+ * @memberof Loader
797
+ */
798
+ static LoadControllers(app) {
799
+ const controllerList = koatty_container.IOCContainer.listClass("CONTROLLER");
800
+ const controllers = {};
801
+ controllerList.forEach((item) => {
802
+ var _a;
803
+ item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("CONTROLLER:", "");
804
+ if (item.id && koatty_lib.Helper.isClass(item.target)) {
805
+ Logger.Debug(`Load controller: ${item.id}`);
806
+ // registering to IOC
807
+ koatty_container.IOCContainer.reg(item.id, item.target, { scope: "Prototype", type: "CONTROLLER", args: [] });
808
+ const ctl = koatty_container.IOCContainer.getInsByClass(item.target);
809
+ if (!(ctl instanceof BaseController)) {
810
+ throw new Error(`class ${item.id} does not inherit from BaseController`);
811
+ }
812
+ controllers[item.id] = 1;
813
+ }
814
+ });
815
+ app.setMetaData("_controllers", controllers);
816
+ }
817
+ /**
818
+ * Load services
819
+ *
820
+ * @static
821
+ * @param {*} app
822
+ * @memberof Loader
823
+ */
824
+ static LoadServices(app) {
825
+ const serviceList = koatty_container.IOCContainer.listClass("SERVICE");
826
+ serviceList.forEach((item) => {
827
+ var _a;
828
+ item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("SERVICE:", "");
829
+ if (item.id && koatty_lib.Helper.isClass(item.target)) {
830
+ Logger.Debug(`Load service: ${item.id}`);
831
+ // registering to IOC
832
+ koatty_container.IOCContainer.reg(item.id, item.target, { scope: "Singleton", type: "SERVICE", args: [] });
833
+ const ctl = koatty_container.IOCContainer.getInsByClass(item.target);
834
+ if (!(ctl instanceof BaseService)) {
835
+ throw new Error(`class ${item.id} does not inherit from BaseService`);
836
+ }
837
+ }
838
+ });
839
+ }
840
+ /**
841
+ * Load components
842
+ *
843
+ * @static
844
+ * @param {*} app
845
+ * @memberof Loader
846
+ */
847
+ static LoadComponents(app) {
848
+ const componentList = koatty_container.IOCContainer.listClass("COMPONENT");
849
+ componentList.forEach((item) => {
850
+ var _a;
851
+ item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("COMPONENT:", "");
852
+ if (item.id && !(item.id).endsWith("Plugin") && koatty_lib.Helper.isClass(item.target)) {
853
+ Logger.Debug(`Load component: ${item.id}`);
854
+ // inject schedule
855
+ // injectSchedule(item.target, item.target.prototype, IOCContainer);
856
+ // registering to IOC
857
+ koatty_container.IOCContainer.reg(item.id, item.target, { scope: "Singleton", type: "COMPONENT", args: [] });
858
+ }
859
+ });
860
+ }
861
+ /**
862
+ * Load plugins
863
+ *
864
+ * @static
865
+ * @param {*} app
866
+ * @memberof Loader
867
+ */
868
+ static async LoadPlugins(app) {
869
+ var _a;
870
+ const componentList = koatty_container.IOCContainer.listClass("COMPONENT");
871
+ let pluginsConf = app.config(undefined, "plugin");
872
+ if (koatty_lib.Helper.isEmpty(pluginsConf)) {
873
+ pluginsConf = { config: {}, list: [] };
874
+ }
875
+ const pluginList = [];
876
+ componentList.forEach(async (item) => {
877
+ var _a;
878
+ item.id = ((_a = item.id) !== null && _a !== void 0 ? _a : "").replace("COMPONENT:", "");
879
+ if (item.id && (item.id).endsWith("Plugin") && koatty_lib.Helper.isClass(item.target)) {
880
+ // Logger.Debug(`Load plugin: ${item.id}`);
881
+ // registering to IOC
882
+ koatty_container.IOCContainer.reg(item.id, item.target, { scope: "Singleton", type: "COMPONENT", args: [] });
883
+ pluginList.push(item.id);
884
+ }
885
+ });
886
+ const pluginConfList = pluginsConf.list;
887
+ if (pluginList.length > pluginConfList.length) {
888
+ Logger.Warn("Some plugins is loaded but not allowed to execute.");
889
+ }
890
+ for (const key of pluginConfList) {
891
+ const handle = koatty_container.IOCContainer.get(key, "COMPONENT");
892
+ if (!koatty_lib.Helper.isFunction(handle.run)) {
893
+ Logger.Error(`plugin ${key} must be implements method 'run'.`);
894
+ continue;
895
+ }
896
+ if (pluginsConf.config[key] === false) {
897
+ continue;
898
+ }
899
+ // Logger.Debug(`Execute plugin: ${key}`);
900
+ // sync exec
901
+ await handle.run((_a = pluginsConf.config[key]) !== null && _a !== void 0 ? _a : {}, app);
902
+ }
903
+ }
904
+ }
905
+
906
+ var version = "3.5.12-0";
907
+ var engines = {
908
+ node: ">12.0.0"
909
+ };
910
+
911
+ /*
912
+ * @Description:
913
+ * @Usage:
914
+ * @Author: richen
915
+ * @Date: 2021-12-17 11:54:06
916
+ * @LastEditTime: 2021-12-17 13:13:00
917
+ */
918
+ const KOATTY_VERSION = version;
919
+ const ENGINES_VERSION = engines.node.slice(1) || '12.0.0';
920
+ /**
921
+ * check node version
922
+ * @return {void} []
923
+ */
924
+ function checkRuntime() {
925
+ let nodeEngines = ENGINES_VERSION;
926
+ nodeEngines = nodeEngines.slice(0, nodeEngines.lastIndexOf('.'));
927
+ let nodeVersion = process.version;
928
+ if (nodeVersion[0] === 'v') {
929
+ nodeVersion = nodeVersion.slice(1);
930
+ }
931
+ nodeVersion = nodeVersion.slice(0, nodeVersion.lastIndexOf('.'));
932
+ if (koatty_lib.Helper.toNumber(nodeEngines) > koatty_lib.Helper.toNumber(nodeVersion)) {
933
+ Logger.Error(`Koatty need node version > ${nodeEngines}, current version is ${nodeVersion}, please upgrade it.`);
934
+ process.exit(-1);
935
+ }
936
+ }
937
+
938
+ /**
939
+ * @ author: richen
940
+ * @ copyright: Copyright (c) - <richenlin(at)gmail.com>
941
+ * @ license: BSD (3-Clause)
942
+ * @ version: 2020-07-06 11:22:58
943
+ */
944
+ /**
945
+ * execute bootstrap
946
+ *
947
+ * @param {*} target
948
+ * @param {Function} bootFunc
949
+ * @returns {Promise<void>}
950
+ */
951
+ const ExecBootstrap = async function (target, bootFunc) {
952
+ // checked runtime
953
+ checkRuntime();
954
+ const app = Reflect.construct(target, []);
955
+ try {
956
+ console.log(LOGO);
957
+ if (!(app instanceof koatty_core.Koatty)) {
958
+ throw new Error(`class ${target.name} does not inherit from Koatty`);
959
+ }
960
+ // version
961
+ koatty_lib.Helper.define(app, "version", KOATTY_VERSION);
962
+ // Initialize env
963
+ Loader.initialize(app);
964
+ // exec bootFunc
965
+ if (koatty_lib.Helper.isFunction(bootFunc)) {
966
+ Logger.Log('think', '', 'Execute bootFunc ...');
967
+ await bootFunc(app);
968
+ }
969
+ // Set IOCContainer.app
970
+ koatty_container.IOCContainer.setApp(app);
971
+ Logger.Log('think', '', 'ComponentScan ...');
972
+ // Check all bean
973
+ Loader.CheckAllComponents(app, target);
974
+ // Load configuration
975
+ Logger.Log('think', '', 'Load Configurations ...');
976
+ // configuration metadata
977
+ const configurationMetas = Loader.GetConfigurationMetas(app, target);
978
+ Loader.LoadConfigs(app, configurationMetas);
979
+ // Load Plugin
980
+ Logger.Log('think', '', 'Load Plugins ...');
981
+ await Loader.LoadPlugins(app);
982
+ // Set Logger
983
+ Loader.SetLogger(app);
984
+ // app.emit("appBoot");
985
+ await asyncEvent(app, 'appBoot');
986
+ // Load App ready hooks
987
+ Loader.LoadAppReadyHooks(app, target);
988
+ // New router
989
+ const KoattyRouter = newRouter(app);
990
+ // Load Middleware
991
+ Logger.Log('think', '', 'Load Middlewares ...');
992
+ await Loader.LoadMiddlewares(app);
993
+ // Load Components
994
+ Logger.Log('think', '', 'Load Components ...');
995
+ Loader.LoadComponents(app);
996
+ // Load Services
997
+ Logger.Log('think', '', 'Load Services ...');
998
+ Loader.LoadServices(app);
999
+ // Load Controllers
1000
+ Logger.Log('think', '', 'Load Controllers ...');
1001
+ Loader.LoadControllers(app);
1002
+ // Emit app ready event
1003
+ Logger.Log('think', '', 'Emit App Ready ...');
1004
+ // app.emit("appReady");
1005
+ await asyncEvent(app, 'appReady');
1006
+ // Load Routers
1007
+ Logger.Log('think', '', 'Load Routers ...');
1008
+ KoattyRouter.LoadRouter(app.getMetaData("_controllers"));
1009
+ // Emit app started event
1010
+ Logger.Log('think', '', 'Emit App Start ...');
1011
+ // app.emit("appStart");
1012
+ const server = newServe(app);
1013
+ await asyncEvent(app, 'appStart');
1014
+ Logger.Log('think', '', '====================================');
1015
+ // Start server
1016
+ app.listen(server);
1017
+ // binding event "appStop"
1018
+ koatty_serve.BindProcessEvent(app, 'appStop');
1019
+ }
1020
+ catch (err) {
1021
+ Logger.Error(err);
1022
+ process.exit();
1023
+ }
1024
+ };
1025
+ /**
1026
+ * create router
1027
+ *
1028
+ * @export
1029
+ * @param {Koatty} app
1030
+ * @returns {*}
1031
+ */
1032
+ const newRouter = function (app) {
1033
+ var _a;
1034
+ const protocol = app.config("protocol") || "http";
1035
+ const options = (_a = app.config(undefined, 'router')) !== null && _a !== void 0 ? _a : {};
1036
+ const router = koatty_router.NewRouter(app, options, protocol);
1037
+ koatty_lib.Helper.define(app, "router", router);
1038
+ return router;
1039
+ };
1040
+ /**
1041
+ * create serve
1042
+ *
1043
+ * @param {Koatty} app
1044
+ * @returns {*}
1045
+ */
1046
+ const newServe = function (app) {
1047
+ const protocol = app.config("protocol") || "http";
1048
+ const server = koatty_serve.Serve(app, protocol);
1049
+ koatty_lib.Helper.define(app, "server", server);
1050
+ return server;
1051
+ };
1052
+ /**
1053
+ * Execute event as async
1054
+ *
1055
+ * @param {Koatty} event
1056
+ * @param {string} eventName
1057
+ */
1058
+ const asyncEvent = async function (event, eventName) {
1059
+ const ls = event.listeners(eventName);
1060
+ // eslint-disable-next-line no-restricted-syntax
1061
+ for await (const func of ls) {
1062
+ if (koatty_lib.Helper.isFunction(func)) {
1063
+ func();
1064
+ }
1065
+ }
1066
+ return event.removeAllListeners(eventName);
1067
+ };
1068
+ /**
1069
+ * Bootstrap application
1070
+ *
1071
+ * @export
1072
+ * @param {Function} [bootFunc]
1073
+ * @returns {ClassDecorator}
1074
+ */
1075
+ function Bootstrap(bootFunc) {
1076
+ return function (target) {
1077
+ if (!(target.prototype instanceof koatty_core.Koatty)) {
1078
+ throw new Error(`class does not inherit from Koatty`);
1079
+ }
1080
+ ExecBootstrap(target, bootFunc);
1081
+ };
1082
+ }
1083
+ /**
1084
+ * Define project scan path
1085
+ *
1086
+ * @export
1087
+ * @param {(string | string[])} [scanPath]
1088
+ * @returns {ClassDecorator}
1089
+ */
1090
+ function ComponentScan(scanPath) {
1091
+ Logger.Log('think', '', 'ComponentScan');
1092
+ return (target) => {
1093
+ if (!(target.prototype instanceof koatty_core.Koatty)) {
1094
+ throw new Error(`class does not inherit from Koatty`);
1095
+ }
1096
+ scanPath = scanPath !== null && scanPath !== void 0 ? scanPath : '';
1097
+ koatty_container.IOCContainer.saveClassMetadata(koatty_container.TAGGED_CLS, COMPONENT_SCAN, scanPath, target);
1098
+ };
1099
+ }
1100
+ /**
1101
+ * Define project configuration scan path
1102
+ *
1103
+ * @export
1104
+ * @param {(string | string[])} [scanPath]
1105
+ * @returns {ClassDecorator}
1106
+ */
1107
+ function ConfigurationScan(scanPath) {
1108
+ Logger.Log('think', '', 'ConfigurationScan');
1109
+ return (target) => {
1110
+ if (!(target.prototype instanceof koatty_core.Koatty)) {
1111
+ throw new Error(`class does not inherit from Koatty`);
1112
+ }
1113
+ scanPath = scanPath !== null && scanPath !== void 0 ? scanPath : '';
1114
+ koatty_container.IOCContainer.saveClassMetadata(koatty_container.TAGGED_CLS, CONFIGURATION_SCAN, scanPath, target);
1115
+ };
1116
+ }
1117
+ /**
1118
+ * bind AppReadyHookFunc
1119
+ * example:
1120
+ * export function TestDecorator(): ClassDecorator {
1121
+ * return (target: any) => {
1122
+ * BindAppReadyHook((app: Koatty) => {
1123
+ * // todo
1124
+ * return Promise.resolve();
1125
+ * }, target)
1126
+ * }
1127
+ * }
1128
+ *
1129
+ * @export
1130
+ * @param {AppReadyHookFunc} func
1131
+ * @param {*} target
1132
+ */
1133
+ function BindAppReadyHook(func, target) {
1134
+ koatty_container.IOCContainer.attachClassMetadata(koatty_container.TAGGED_CLS, APP_READY_HOOK, func, target);
1135
+ }
1136
+
1137
+ /**
1138
+ * @ author: richen
1139
+ * @ copyright: Copyright (c) - <richenlin(at)gmail.com>
1140
+ * @ license: BSD (3-Clause)
1141
+ * @ version: 2020-05-10 11:32:45
1142
+ */
1143
+ /**
1144
+ * Indicates that an decorated class is a "component".
1145
+ *
1146
+ * @export
1147
+ * @param {string} [identifier] component name
1148
+ * @returns {ClassDecorator}
1149
+ */
1150
+ function Component(identifier) {
1151
+ return (target) => {
1152
+ identifier = identifier || koatty_container.IOCContainer.getIdentifier(target);
1153
+ koatty_container.IOCContainer.saveClass("COMPONENT", target, identifier);
1154
+ };
1155
+ }
1156
+ /**
1157
+ * Indicates that an decorated class is a "controller".
1158
+ *
1159
+ * @export
1160
+ * @param {string} [path] controller router path
1161
+ * @returns {ClassDecorator}
1162
+ */
1163
+ function Controller(path = "") {
1164
+ return (target) => {
1165
+ const identifier = koatty_container.IOCContainer.getIdentifier(target);
1166
+ koatty_container.IOCContainer.saveClass("CONTROLLER", target, identifier);
1167
+ koatty_container.IOCContainer.savePropertyData(koatty_router.CONTROLLER_ROUTER, path, target, identifier);
1168
+ };
1169
+ }
1170
+ /**
1171
+ * Indicates that an decorated class is a "middleware".
1172
+ *
1173
+ * @export
1174
+ * @param {string} [identifier] middleware name
1175
+ * @returns {ClassDecorator}
1176
+ */
1177
+ function Middleware(identifier) {
1178
+ return (target) => {
1179
+ identifier = identifier || koatty_container.IOCContainer.getIdentifier(target);
1180
+ koatty_container.IOCContainer.saveClass("MIDDLEWARE", target, identifier);
1181
+ };
1182
+ }
1183
+ /**
1184
+ * Indicates that an decorated class is a "service".
1185
+ *
1186
+ * @export
1187
+ * @param {string} [identifier] middleware name
1188
+ * @returns {ClassDecorator}
1189
+ */
1190
+ function Service(identifier) {
1191
+ return (target) => {
1192
+ identifier = identifier || koatty_container.IOCContainer.getIdentifier(target);
1193
+ koatty_container.IOCContainer.saveClass("SERVICE", target, identifier);
1194
+ };
1195
+ }
1196
+ /**
1197
+ * Indicates that an decorated class is a "plugin".
1198
+ *
1199
+ * @export
1200
+ * @param {string} [identifier]
1201
+ * @returns {ClassDecorator}
1202
+ */
1203
+ function Plugin(identifier) {
1204
+ return (target) => {
1205
+ identifier = identifier || koatty_container.IOCContainer.getIdentifier(target);
1206
+ //
1207
+ if (!identifier.endsWith("Plugin")) {
1208
+ throw Error("Plugin class name must be 'Plugin' suffix.");
1209
+ }
1210
+ koatty_container.IOCContainer.saveClass("COMPONENT", target, `${identifier}`);
1211
+ };
1212
+ }
1213
+
1214
+ Object.defineProperty(exports, 'Helper', {
1215
+ enumerable: true,
1216
+ get: function () { return koatty_lib.Helper; }
1217
+ });
1218
+ exports.BaseController = BaseController;
1219
+ exports.BaseService = BaseService;
1220
+ exports.BindAppReadyHook = BindAppReadyHook;
1221
+ exports.Bootstrap = Bootstrap;
1222
+ exports.Component = Component;
1223
+ exports.ComponentScan = ComponentScan;
1224
+ exports.ConfigurationScan = ConfigurationScan;
1225
+ exports.Controller = Controller;
1226
+ exports.HttpController = HttpController;
1227
+ exports.Logger = Logger;
1228
+ exports.Middleware = Middleware;
1229
+ exports.Plugin = Plugin;
1230
+ exports.Service = Service;
1231
+ Object.keys(koatty_router).forEach(function (k) {
1232
+ if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1233
+ enumerable: true,
1234
+ get: function () { return koatty_router[k]; }
1235
+ });
1236
+ });
1237
+ Object.keys(koatty_core).forEach(function (k) {
1238
+ if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1239
+ enumerable: true,
1240
+ get: function () { return koatty_core[k]; }
1241
+ });
1242
+ });
1243
+ Object.keys(koatty_serve).forEach(function (k) {
1244
+ if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1245
+ enumerable: true,
1246
+ get: function () { return koatty_serve[k]; }
1247
+ });
1248
+ });
1249
+ Object.keys(koatty_container).forEach(function (k) {
1250
+ if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1251
+ enumerable: true,
1252
+ get: function () { return koatty_container[k]; }
1253
+ });
1254
+ });
1255
+ Object.keys(koatty_exception).forEach(function (k) {
1256
+ if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1257
+ enumerable: true,
1258
+ get: function () { return koatty_exception[k]; }
1259
+ });
1260
+ });
1261
+ Object.keys(koatty_trace).forEach(function (k) {
1262
+ if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
1263
+ enumerable: true,
1264
+ get: function () { return koatty_trace[k]; }
1265
+ });
1266
+ });