koatty 3.13.2 → 4.0.3

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.
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /*!
2
2
  * @Author: richen
3
- * @Date: 2025-04-25 21:47:59
3
+ * @Date: 2026-01-28 11:05:04
4
4
  * @License: BSD (3-Clause)
5
5
  * @Copyright (c) - <richenlin(at)gmail.com>
6
6
  * @HomePage: https://koatty.org/
@@ -9,36 +9,38 @@ import { LoadConfigs as t } from "koatty_config";
9
9
 
10
10
  export { Config } from "koatty_config";
11
11
 
12
- import { IOC as e, TAGGED_CLS as o } from "koatty_container";
12
+ import { IOC as o, TAGGED_CLS as e } from "koatty_container";
13
13
 
14
14
  export * from "koatty_container";
15
15
 
16
- import { AppEventArr as a, implementsMiddlewareInterface as s, parseExp as r, implementsControllerInterface as i, implementsServiceInterface as n, implementsPluginInterface as l, implementsAspectInterface as c, Koatty as p, asyncEvent as d } from "koatty_core";
16
+ import { AppEvent as a, AppEventArr as r, asyncEvent as i, ComponentManager as s, implementsMiddlewareInterface as n, MIDDLEWARE_OPTIONS as l, protocolMiddleware as c, implementsControllerInterface as d, implementsServiceInterface as p, implementsAspectInterface as f, Koatty as g } from "koatty_core";
17
17
 
18
18
  export * from "koatty_core";
19
19
 
20
20
  export * from "koatty_exception";
21
21
 
22
- import { Helper as f } from "koatty_lib";
22
+ import { Helper as u } from "koatty_lib";
23
23
 
24
24
  export { Helper } from "koatty_lib";
25
25
 
26
- import { NewRouter as g } from "koatty_router";
26
+ import { NewRouter as L } from "koatty_router";
27
27
 
28
28
  export * from "koatty_router";
29
29
 
30
- import { DefaultLogger as u } from "koatty_logger";
30
+ import { DefaultLogger as y } from "koatty_logger";
31
31
 
32
- import { Load as h } from "koatty_loader";
32
+ import { Load as m } from "koatty_loader";
33
33
 
34
- import { NewServe as m } from "koatty_serve";
34
+ import { NewServe as h } from "koatty_serve";
35
35
 
36
- import * as y from "path";
36
+ import { Trace as v } from "koatty_trace";
37
37
 
38
- var L = "3.13.2";
38
+ import * as w from "path";
39
39
 
40
- var v = {
41
- node: ">12.0.0"
40
+ var C = "4.0.3";
41
+
42
+ var E = {
43
+ node: ">=18.0.0"
42
44
  };
43
45
 
44
46
  /*
@@ -49,16 +51,25 @@ var v = {
49
51
  * @LastEditTime: 2024-10-31 17:52:43
50
52
  * @License: BSD (3-Clause)
51
53
  * @Copyright (c): <richenlin(at)gmail.com>
52
- */ const w = u;
53
-
54
- function C(t, e) {
55
- if (e.logLevel) u.setLevel(e.logLevel);
56
- if (e.logFilePath && !t.silent) {
57
- f.define(t, "logsPath", e.logFilePath);
58
- process.env.LOGS_PATH = e.logFilePath;
59
- u.setLogFilePath(e.logFilePath);
54
+ */ const K = y;
55
+
56
+ function P(t, o) {
57
+ if (!t.appDebug) y.enableBuffering({
58
+ maxBufferSize: 200,
59
+ flushInterval: 500,
60
+ flushOnLevel: "error"
61
+ });
62
+ if (o.logLevel) y.setLevel(o.logLevel);
63
+ if (o.logFilePath && !t.silent) {
64
+ u.define(t, "logsPath", o.logFilePath);
65
+ process.env.LOGS_PATH = o.logFilePath;
66
+ y.setLogFilePath(o.logFilePath);
60
67
  }
61
- if (e.sensFields) u.setSensFields(e.sensFields);
68
+ if (o.sensFields) y.setSensFields(o.sensFields);
69
+ t.once(a.appStop, async () => {
70
+ await y.flush();
71
+ await y.destroy();
72
+ });
62
73
  }
63
74
 
64
75
  /*
@@ -69,38 +80,38 @@ function C(t, e) {
69
80
  * @LastEditTime: 2025-01-14 16:14:10
70
81
  * @License: BSD (3-Clause)
71
82
  * @Copyright (c): <richenlin(at)gmail.com>
72
- */ const E = L;
83
+ */ const b = C;
73
84
 
74
- const P = v.node.slice(1) || "12.0.0";
85
+ const M = E.node.slice(1) || "12.0.0";
75
86
 
76
- function A(t, e, o, a) {
77
- if (f.isClass(o) && o.name != t) throw Error(`The file(${e}) name should be always the same as class name.`);
78
- if (o["__esModule"]) if (o.name === void 0) {
79
- const a = Object.keys(o);
80
- if (a[0] != t && f.isClass(o[a[0]])) throw Error(`The file(${e}) name should be always the same as class name.`);
81
- } else if (o.name != t) throw Error(`The file(${e}) name should be always the same as class name.`);
87
+ function R(t, o, e, a) {
88
+ if (u.isClass(e) && e.name != t) throw Error(`The file(${o}) name should be always the same as class name.`);
89
+ if (e["__esModule"]) if (e.name === void 0) {
90
+ const a = Object.keys(e);
91
+ if (a[0] != t && u.isClass(e[a[0]])) throw Error(`The file(${o}) name should be always the same as class name.`);
92
+ } else if (e.name != t) throw Error(`The file(${o}) name should be always the same as class name.`);
82
93
  if (!a) return;
83
- if (a.has(t)) throw new Error(`A same class already exists. at \`${e}\`.`);
94
+ if (a.has(t)) throw new Error(`A same class already exists. at \`${o}\`.`);
84
95
  a.add(t);
85
96
  return;
86
97
  }
87
98
 
88
- function M() {
89
- let t = P;
99
+ function S() {
100
+ let t = M;
90
101
  t = t.slice(0, t.lastIndexOf("."));
91
- let e = process.version;
92
- if (e[0] === "v") e = e.slice(1);
93
- e = e.slice(0, e.lastIndexOf("."));
94
- if (f.toNumber(t) > f.toNumber(e)) {
95
- w.Error(`Koatty need node version > ${t}, current version is ${e}, please upgrade it.`);
102
+ let o = process.version;
103
+ if (o[0] === "v") o = o.slice(1);
104
+ o = o.slice(0, o.lastIndexOf("."));
105
+ if (u.toNumber(t) > u.toNumber(o)) {
106
+ K.Fatal(`Koatty need node version > ${t}, current version is ${o}, please upgrade it.`);
96
107
  process.exit(-1);
97
108
  }
98
109
  }
99
110
 
100
- const $ = () => {
111
+ const A = () => {
101
112
  let t = !1;
102
- const e = JSON.stringify(process.argv[1]);
103
- if (e.indexOf("jest") > -1) t = !0;
113
+ const o = JSON.stringify(process.argv[1]);
114
+ if (o.indexOf("jest") > -1) t = !0;
104
115
  return t;
105
116
  };
106
117
 
@@ -112,11 +123,11 @@ const $ = () => {
112
123
  * @LastEditTime: 2023-12-09 23:00:13
113
124
  * @License: BSD (3-Clause)
114
125
  * @Copyright (c): <richenlin(at)gmail.com>
115
- */ const R = "COMPONENT_SCAN";
126
+ */ const k = "COMPONENT_SCAN";
116
127
 
117
- const k = "CONFIGURATION_SCAN";
128
+ const $ = "CONFIGURATION_SCAN";
118
129
 
119
- const T = `\n\n┬┌─┌─┐┌─┐┌┬┐┌┬┐┬ ┬\n├┴┐│ │├─┤ │ │ └┬┘\n┴ ┴└─┘┴ ┴ ┴ ┴ ┴ \n-------------------------------------------\nhttps://github.com/koatty\n`
130
+ const O = `\n\n┬┌─┌─┐┌─┐┌┬┐┌┬┐┬ ┬\n├┴┐│ │├─┤ │ │ └┬┘\n┴ ┴└─┘┴ ┴ ┴ ┴ ┴ \n-------------------------------------------\nhttps://github.com/koatty\n`
120
131
  /*
121
132
  * @Description: framework loader
122
133
  * @Usage:
@@ -132,261 +143,368 @@ class Loader {
132
143
  this.app = t;
133
144
  }
134
145
  static initialize(t) {
135
- if (t.env == "development") w.setLevel("debug"); else w.setLevel("info");
136
- const e = t.rootPath || process.cwd();
137
- const o = t.appPath || y.resolve(e, t.appDebug ? "src" : "dist");
138
- const a = y.resolve(__dirname, "..");
139
- f.define(t, "rootPath", e);
140
- f.define(t, "appPath", o);
141
- f.define(t, "koattyPath", a);
142
- if (f.isEmpty(t.name)) {
143
- const e = f.safeRequire(`${y.dirname(o)}/package.json`);
144
- if (e.name) {
145
- t.name = e.name;
146
- t.version = t.version || e.version;
146
+ if (t.env == "development") K.setLevel("debug"); else K.setLevel("info");
147
+ const o = t.rootPath || process.cwd();
148
+ const e = t.appPath || w.resolve(o, t.appDebug ? "src" : "dist");
149
+ const a = w.resolve(__dirname, "..");
150
+ u.define(t, "rootPath", o);
151
+ u.define(t, "appPath", e);
152
+ u.define(t, "koattyPath", a);
153
+ if (u.isEmpty(t.name)) {
154
+ const o = u.safeRequire(`${w.dirname(e)}/package.json`);
155
+ if (o.name) {
156
+ t.name = o.name;
157
+ t.version = t.version || o.version;
147
158
  }
148
159
  }
149
- process.env.ROOT_PATH = e;
150
- process.env.APP_PATH = o;
160
+ K.Warn("Using process.env for paths is deprecated. Use app.rootPath, app.appPath, app.koattyPath instead.");
161
+ process.env.ROOT_PATH = o;
162
+ process.env.APP_PATH = e;
151
163
  process.env.KOATTY_PATH = a;
152
- f.define(t, "thinkPath", a);
164
+ u.define(t, "thinkPath", a);
153
165
  process.env.THINK_PATH = a;
154
166
  }
155
167
  static GetComponentMeta(t, a) {
156
- let s = [];
157
- const r = e.getClassMetadata(o, R, a);
158
- if (r) if (f.isArray(r)) s = r; else s.push(r);
159
- if (s.length < 1) s = [ t.appPath ];
160
- return s;
161
- }
162
- static GetConfigurationMeta(t, a) {
163
- const s = e.getClassMetadata(o, k, a);
164
168
  let r = [];
165
- if (s) if (f.isArray(s)) r = s; else r.push(s);
169
+ const i = o.getClassMetadata(e, k, a);
170
+ if (i) if (u.isArray(i)) r = i; else r.push(i);
171
+ if (r.length < 1) r = [ t.appPath ];
166
172
  return r;
167
173
  }
168
- static CheckAllComponents(t, e) {
169
- const o = Loader.GetComponentMeta(t, e);
170
- const a = Loader.GetConfigurationMeta(t, e);
171
- const s = new Set;
172
- h(o, "", ((t, e, o) => {
173
- A(t, e, o, s);
174
- }), [ "**/**.js", "**/**.ts", "!**/**.d.ts" ], [ ...a, `${e.name || ".no"}.ts` ]);
175
- s.clear();
174
+ static GetConfigurationMeta(t, a) {
175
+ const r = o.getClassMetadata(e, $, a);
176
+ let i = [];
177
+ if (r) if (u.isArray(r)) i = r; else i.push(r);
178
+ return i;
179
+ }
180
+ static CheckAllComponents(t, o) {
181
+ const e = Loader.GetComponentMeta(t, o);
182
+ const a = Loader.GetConfigurationMeta(t, o);
183
+ const r = new Set;
184
+ m(e, "", (t, o, e) => {
185
+ R(t, o, e, r);
186
+ }, [ "**/**.js", "**/**.ts", "!**/**.d.ts" ], [ ...a, `${o.name || ".no"}.ts` ]);
187
+ r.clear();
176
188
  }
177
189
  static SetLogger(t) {
178
- const e = t.getMetaData("_configs") || [];
179
- const o = e[0] || {};
180
- if (o.config) {
181
- const e = o.config;
182
- let a = "debug", s = "", r = [];
190
+ const o = t.getMetaData("_configs") || [];
191
+ const e = o[0] || {};
192
+ if (e.config) {
193
+ const o = e.config;
194
+ let a = "debug", r = "", i = [];
183
195
  if (t.env === "production") a = "info";
184
- if (e.logsLevel) a = e.logsLevel.toLowerCase();
185
- if (e.logsPath) s = e.logsPath;
186
- if (e.sensFields) r = e.sensFields;
187
- C(t, {
196
+ if (o.logsLevel) a = o.logsLevel.toLowerCase();
197
+ if (o.logsPath) r = o.logsPath;
198
+ if (o.sensFields) i = o.sensFields;
199
+ P(t, {
188
200
  logLevel: a,
189
- logFilePath: s,
190
- sensFields: r
201
+ logFilePath: r,
202
+ sensFields: i
191
203
  });
192
204
  }
193
205
  }
194
- static LoadAppEventHooks(t, s) {
195
- const r = new Map;
196
- for (const t of a) {
197
- let a;
206
+ static LoadAppEventHooks(t, i) {
207
+ const s = new Map;
208
+ for (const t of r) {
209
+ let r;
198
210
  switch (t) {
199
- case "appBoot":
200
- a = e.getClassMetadata(o, "appBoot", s);
201
- if (f.isArray(a)) r.set("appBoot", a);
211
+ case a.appBoot:
212
+ r = o.getClassMetadata(e, a.appBoot, i);
213
+ if (u.isArray(r)) s.set(a.appBoot, r);
202
214
  break;
203
215
 
204
- case "appReady":
205
- a = e.getClassMetadata(o, "appReady", s);
206
- if (f.isArray(a)) r.set("appReady", a);
216
+ case a.appReady:
217
+ r = o.getClassMetadata(e, a.appReady, i);
218
+ if (u.isArray(r)) s.set(a.appReady, r);
207
219
  break;
208
220
 
209
- case "appStart":
210
- a = e.getClassMetadata(o, "appStart", s);
211
- if (f.isArray(a)) r.set("appStart", a);
221
+ case a.appStart:
222
+ r = o.getClassMetadata(e, a.appStart, i);
223
+ if (u.isArray(r)) s.set(a.appStart, r);
212
224
  break;
213
225
 
214
- case "appStop":
215
- a = e.getClassMetadata(o, "appStop", s);
216
- if (f.isArray(a)) r.set("appStop", a);
226
+ case a.appStop:
227
+ r = o.getClassMetadata(e, a.appStop, i);
228
+ if (u.isArray(r)) s.set(a.appStop, r);
217
229
  break;
218
230
  }
219
231
  }
220
- for (const [e, o] of r) for (const a of o) t.once(e, (() => a(t)));
232
+ for (const [o, e] of s) for (const a of e) t.once(o, () => a(t));
221
233
  }
222
234
  static async LoadAllComponents(t, e) {
223
- var o, a, s;
224
- w.Log("Koatty", "", "Load Configurations ...");
235
+ try {
236
+ if (u.isFunction(o.preloadMetadata)) o.preloadMetadata();
237
+ } catch {
238
+ K.Warn("[Loader] preloadMetadata is optional, ignore if not available");
239
+ }
240
+ K.Log("Koatty", "", "Load Configurations ...");
225
241
  const r = Loader.GetConfigurationMeta(t, e);
226
- const i = new Loader(t);
227
- i.LoadConfigs(r);
228
- const n = (o = t.config("server")) !== null && o !== void 0 ? o : {
229
- protocol: "http"
230
- };
231
- const l = (a = n.protocol) !== null && a !== void 0 ? a : "http";
232
- f.define(t, "server", m(t, n));
233
- const c = (s = t.config(void 0, "router")) !== null && s !== void 0 ? s : {};
234
- f.define(t, "router", g(t, {
235
- protocol: l,
236
- ...c
237
- }));
238
- w.Log("Koatty", "", "Load Components ...");
239
- await i.LoadComponents();
240
- w.Log("Koatty", "", "Load Middlewares ...");
241
- await i.LoadMiddlewares();
242
- w.Log("Koatty", "", "Load Services ...");
243
- await i.LoadServices();
244
- w.Log("Koatty", "", "Load Controllers ...");
245
- const p = await i.LoadControllers();
246
- w.Log("Koatty", "", "Load Routers ...");
247
- i.LoadRouter(p);
242
+ const n = new Loader(t);
243
+ n.LoadConfigs(r);
244
+ Loader.SetLogger(t);
245
+ K.Log("Koatty", "", "Emit Config Loaded ...");
246
+ await i(t, a.configLoaded);
247
+ K.Log("Koatty", "", "Initializing Component Manager ...");
248
+ const l = new s(t);
249
+ u.define(t, "componentManager", l);
250
+ l.discoverPlugins();
251
+ l.registerCorePluginHooks();
252
+ const c = l.getStats();
253
+ K.Log("Koatty", "", `Discovered ${c.corePlugins} core plugins, ${c.userPlugins} user plugins`);
254
+ K.Log("Koatty", "", "Emit Before Component Load ...");
255
+ await i(t, a.beforeComponentLoad);
256
+ K.Log("Koatty", "", "Load Components ...");
257
+ await n.LoadComponents(l);
258
+ K.Log("Koatty", "", "Emit After Component Load ...");
259
+ await i(t, a.afterComponentLoad);
260
+ K.Log("Koatty", "", "Emit Before Middleware Load ...");
261
+ await i(t, a.beforeMiddlewareLoad);
262
+ K.Log("Koatty", "", "Load Middlewares ...");
263
+ await n.LoadMiddlewares();
264
+ K.Log("Koatty", "", "Emit After Middleware Load ...");
265
+ await i(t, a.afterMiddlewareLoad);
266
+ K.Log("Koatty", "", "Emit Before Service Load ...");
267
+ await i(t, a.beforeServiceLoad);
268
+ K.Log("Koatty", "", "Load Services ...");
269
+ await n.LoadServices();
270
+ K.Log("Koatty", "", "Emit After Service Load ...");
271
+ await i(t, a.afterServiceLoad);
272
+ K.Log("Koatty", "", "Emit Before Controller Load ...");
273
+ await i(t, a.beforeControllerLoad);
274
+ K.Log("Koatty", "", "Load Controllers ...");
275
+ const d = await n.LoadControllers();
276
+ K.Log("Koatty", "", "Emit After Controller Load ...");
277
+ await i(t, a.afterControllerLoad);
278
+ K.Log("Koatty", "", "Emit Before Router Load ...");
279
+ await i(t, a.beforeRouterLoad);
280
+ K.Log("Koatty", "", "Load Routers ...");
281
+ await n.LoadRouter(d);
282
+ K.Log("Koatty", "", "Emit After Router Load ...");
283
+ await i(t, a.afterRouterLoad);
248
284
  }
249
- LoadConfigs(e) {
250
- const o = {};
251
- h([ "./config" ], this.app.koattyPath, (function(t, e, a) {
252
- o[t] = a;
253
- }));
254
- if (f.isArray(e)) e = e.length > 0 ? e : [ "./config" ];
255
- let a = t(e, this.app.appPath);
256
- a = f.extend(o, a, !0);
285
+ static CreateServers(t, o, e) {
286
+ if (e.length > 1) {
287
+ const a = [];
288
+ const r = u.isArray(o.port) ? o.port : [ o.port ];
289
+ const i = [];
290
+ for (let t = 0; t < e.length; t++) if (t < r.length) i.push(u.toNumber(r[t])); else i.push(u.toNumber(r[0]) + t);
291
+ for (let r = 0; r < e.length; r++) {
292
+ const s = e[r];
293
+ const n = {
294
+ ...o,
295
+ protocol: s,
296
+ port: i[r]
297
+ };
298
+ a.push(h(t, n));
299
+ }
300
+ return a;
301
+ } else {
302
+ const a = e[0];
303
+ const r = {
304
+ protocol: a,
305
+ ...o
306
+ };
307
+ return h(t, r);
308
+ }
309
+ }
310
+ static CreateRouters(t, o, e) {
311
+ if (e.length > 1) {
312
+ const a = {};
313
+ for (const r of e) {
314
+ const e = {
315
+ protocol: r,
316
+ ...o
317
+ };
318
+ if (o.ext && o.ext[r]) e.ext = o.ext[r];
319
+ a[r] = L(t, e);
320
+ }
321
+ return a;
322
+ } else {
323
+ const a = e[0];
324
+ return L(t, {
325
+ protocol: a,
326
+ ...o
327
+ });
328
+ }
329
+ }
330
+ LoadConfigs(o) {
331
+ const e = {};
332
+ m([ "./config" ], this.app.koattyPath, function(t, o, a) {
333
+ e[t] = a;
334
+ });
335
+ if (u.isArray(o)) o = o.length > 0 ? o : [ "./config" ];
336
+ let a = t(o, this.app.appPath);
337
+ a = u.extend(e, a, !0);
257
338
  this.app.setMetaData("_configs", a);
258
339
  }
259
340
  async LoadMiddlewares() {
260
- var t;
261
- let o = this.app.config(void 0, "middleware");
262
- if (f.isEmpty(o)) o = {
341
+ var t, e, a;
342
+ try {
343
+ const o = (t = this.app.config("trace")) !== null && t !== void 0 ? t : {};
344
+ const e = v(o, this.app);
345
+ u.define(this.app, "tracer", e);
346
+ this.app.use(e);
347
+ K.Debug(`Load trace middleware`);
348
+ } catch (t) {
349
+ K.Warn(`Trace middleware failed to load: ${t.message}`);
350
+ }
351
+ let r = this.app.config(void 0, "middleware");
352
+ if (u.isEmpty(r)) r = {
263
353
  config: {},
264
- list: [],
265
- routeList: []
354
+ list: []
266
355
  };
267
- const a = (t = e.listClass("MIDDLEWARE")) !== null && t !== void 0 ? t : [];
268
- a.forEach((t => {
269
- var o;
270
- t.id = ((o = t.id) !== null && o !== void 0 ? o : "").replace("MIDDLEWARE:", "");
271
- if (t.id && f.isClass(t.target)) {
272
- e.reg(t.id, t.target, {
356
+ const i = (e = o.listClass("MIDDLEWARE")) !== null && e !== void 0 ? e : [];
357
+ i.forEach(t => {
358
+ var e;
359
+ t.id = ((e = t.id) !== null && e !== void 0 ? e : "").replace("MIDDLEWARE:", "");
360
+ if (t.id && u.isClass(t.target)) {
361
+ o.reg(t.id, t.target, {
273
362
  scope: "Prototype",
274
363
  type: "MIDDLEWARE",
275
364
  args: []
276
365
  });
277
- const o = e.getInsByClass(t.target);
278
- if (!s(o)) throw Error(`The middleware ${t.id} must implements interface 'IMiddleware'.`);
366
+ const e = o.getInsByClass(t.target);
367
+ if (!n(e)) throw Error(`The middleware ${t.id} must implements interface 'IMiddleware'.`);
368
+ }
369
+ });
370
+ const s = r.list || [];
371
+ const d = new Set([]);
372
+ s.forEach(t => {
373
+ d.add(t);
374
+ });
375
+ const p = r.config || {};
376
+ for (const t of d) {
377
+ const e = o.get(t, "MIDDLEWARE");
378
+ if (!e) throw Error(`Middleware ${t} load error.`);
379
+ if (!u.isFunction(e.run)) throw Error(`The middleware ${t} must implements interface 'IMiddleware'.`);
380
+ K.Debug(`Load middleware: ${t}`);
381
+ const r = p[t] || {};
382
+ const s = (a = i.find(o => o.id === t)) === null || a === void 0 ? void 0 : a.target;
383
+ let n = {};
384
+ if (s) try {
385
+ n = o.getPropertyData(l, s, t) || {};
386
+ } catch {
387
+ n = {};
388
+ }
389
+ const d = {
390
+ ...n,
391
+ ...r
392
+ };
393
+ if (d.enabled === !1) {
394
+ K.Warn(`The middleware ${t} has been loaded but is disabled.`);
395
+ continue;
396
+ }
397
+ const f = await e.run(d, this.app);
398
+ if (u.isFunction(f)) {
399
+ let o = f;
400
+ if (d.protocol) {
401
+ const e = u.isArray(d.protocol) ? d.protocol : [ d.protocol ];
402
+ K.Log("Koatty", "", `Middleware ${t} limited to protocols: ${e.join(", ")}`);
403
+ o = c(e, f);
404
+ }
405
+ if (o.length < 3) this.app.use(o); else this.app.useExp(o);
279
406
  }
280
- }));
281
- const i = o.list || [];
282
- const n = new Set([]);
283
- i.forEach((t => {
284
- n.add(t);
285
- }));
286
- const l = o.routeList || [];
287
- const c = new Set([]);
288
- l.forEach((t => {
289
- c.add(t);
290
- }));
291
- const p = o.config || {};
292
- for (const t of n) {
293
- const o = e.get(t, "MIDDLEWARE");
294
- if (!o) throw Error(`Middleware ${t} load error.`);
295
- if (!f.isFunction(o.run)) throw Error(`The middleware ${t} must implements interface 'IMiddleware'.`);
296
- w.Debug(`Load middleware: ${t}`);
297
- const a = p[t] || {};
298
- const s = await o.run(a, this.app);
299
- if (f.isFunction(s)) if (s.length < 3) this.app.use(s); else this.app.useExp(s);
300
- }
301
- for (const t of c) {
302
- const o = e.get(t, "MIDDLEWARE");
303
- if (!o) throw Error(`Router middleware ${t} load error.`);
304
- if (!f.isFunction(o.run)) throw Error(`The router middleware ${t} must implements interface 'IMiddleware'.`);
305
- w.Debug(`Load router middleware: ${t}`);
306
- const a = await o.run(p[t] || {}, this.app);
307
- if (f.isFunction(a)) this.app.setMetaData(`routerMiddleware_${t}`, a.length > 2 ? r(a) : a);
308
407
  }
309
408
  }
310
409
  async LoadControllers() {
311
- const t = e.listClass("CONTROLLER");
312
- const o = [];
313
- t.forEach((t => {
410
+ const t = o.listClass("CONTROLLER");
411
+ const e = [];
412
+ t.forEach(t => {
314
413
  var a;
315
414
  t.id = ((a = t.id) !== null && a !== void 0 ? a : "").replace("CONTROLLER:", "");
316
- if (t.id && f.isClass(t.target)) {
317
- w.Debug(`Load controller: ${t.id}`);
318
- e.reg(t.id, t.target, {
415
+ if (t.id && u.isClass(t.target)) {
416
+ K.Debug(`Load controller: ${t.id}`);
417
+ o.reg(t.id, t.target, {
319
418
  scope: "Prototype",
320
419
  type: "CONTROLLER",
321
420
  args: []
322
421
  });
323
- const a = e.getInsByClass(t.target);
324
- if (!i(a)) throw Error(`The controller ${t.id} must implements interface 'IController'.`);
325
- o.push(t.id);
422
+ const a = o.getInsByClass(t.target);
423
+ if (!d(a)) throw Error(`The controller ${t.id} must implements interface 'IController'.`);
424
+ e.push(t.id);
326
425
  }
327
- }));
328
- return o;
426
+ });
427
+ return e;
329
428
  }
330
429
  async LoadServices() {
331
- const t = e.listClass("SERVICE");
332
- t.forEach((t => {
333
- var o;
334
- t.id = ((o = t.id) !== null && o !== void 0 ? o : "").replace("SERVICE:", "");
335
- if (t.id && f.isClass(t.target)) {
336
- w.Debug(`Load service: ${t.id}`);
337
- e.reg(t.id, t.target, {
430
+ var t;
431
+ const e = o.listClass("SERVICE");
432
+ for (const a of e) {
433
+ a.id = ((t = a.id) !== null && t !== void 0 ? t : "").replace("SERVICE:", "");
434
+ if (a.id && u.isClass(a.target)) {
435
+ K.Debug(`Load service: ${a.id}`);
436
+ o.reg(a.id, a.target, {
338
437
  scope: "Singleton",
339
438
  type: "SERVICE",
340
439
  args: []
341
440
  });
342
- const o = e.getInsByClass(t.target);
343
- if (!n(o)) throw Error(`The service ${t.id} must implements interface 'IService'.`);
441
+ const t = o.getInsByClass(a.target);
442
+ if (!p(t)) throw Error(`The service ${a.id} must implements interface 'IService'.`);
344
443
  }
345
- }));
444
+ }
346
445
  }
347
- async LoadComponents() {
348
- var t, o;
349
- const a = e.listClass("COMPONENT");
350
- const s = [];
351
- a.forEach((async t => {
352
- var o;
353
- t.id = ((o = t.id) !== null && o !== void 0 ? o : "").replace("COMPONENT:", "");
354
- if (f.isClass(t.target)) {
355
- e.reg(t.id, t.target, {
446
+ async LoadComponents(t) {
447
+ var e, a;
448
+ const r = o.listClass("COMPONENT");
449
+ r.forEach(t => {
450
+ var e;
451
+ t.id = ((e = t.id) !== null && e !== void 0 ? e : "").replace("COMPONENT:", "");
452
+ if (u.isClass(t.target)) {
453
+ o.reg(t.id, t.target, {
356
454
  scope: "Singleton",
357
455
  type: "COMPONENT",
358
456
  args: []
359
457
  });
360
- if (t.id && t.id.endsWith("Plugin")) {
361
- const o = e.getInsByClass(t.target);
362
- if (!l(o)) throw Error(`The plugin ${t.id} must implements interface 'IPlugin'.`);
363
- s.push(t.id);
364
- }
365
458
  if (t.id && t.id.endsWith("Aspect")) {
366
- const o = e.getInsByClass(t.target);
367
- if (!c(o)) throw Error(`The aspect ${t.id} must implements interface 'IAspect'.`);
459
+ const e = o.getInsByClass(t.target);
460
+ if (!f(e)) throw Error(`The aspect ${t.id} must implements interface 'IAspect'.`);
368
461
  }
369
462
  }
370
- }));
371
- let r = this.app.config(void 0, "plugin");
372
- if (f.isEmpty(r)) r = {
373
- config: {},
374
- list: []
375
- };
376
- const i = (t = r.list) !== null && t !== void 0 ? t : [];
377
- for (const t of i) {
378
- const a = e.get(t, "COMPONENT");
379
- if (!a) throw Error(`Plugin ${t} load error.`);
380
- if (!f.isFunction(a.run)) throw Error(`Plugin ${t} must implements interface 'IPlugin'.`);
381
- if (r.config[t] === !1) {
382
- w.Warn(`Plugin ${t} already loaded but not effective.`);
383
- continue;
463
+ });
464
+ if (t) await t.loadUserPlugins(); else {
465
+ K.Warn("Loading plugins in legacy mode");
466
+ let t = this.app.config(void 0, "plugin");
467
+ if (u.isEmpty(t)) t = {
468
+ config: {},
469
+ list: []
470
+ };
471
+ const r = (e = t.list) !== null && e !== void 0 ? e : [];
472
+ for (const e of r) {
473
+ const r = o.get(e, "COMPONENT");
474
+ if (!r) throw Error(`Plugin ${e} load error.`);
475
+ if (!u.isFunction(r.run)) throw Error(`Plugin ${e} must implements interface 'IPlugin'.`);
476
+ if (t.config[e] === !1) {
477
+ K.Warn(`Plugin ${e} already loaded but not effective.`);
478
+ continue;
479
+ }
480
+ await r.run((a = t.config[e]) !== null && a !== void 0 ? a : {}, this.app);
384
481
  }
385
- await a.run((o = r.config[t]) !== null && o !== void 0 ? o : {}, this.app);
386
482
  }
387
483
  }
388
484
  async LoadRouter(t) {
389
- await this.app.router.LoadRouter(this.app, t);
485
+ var o;
486
+ const e = this.app.router;
487
+ K.Log("Koatty", "", "============ LoadRouter START ============");
488
+ K.Log("Koatty", "", "router type:", typeof e);
489
+ K.Log("Koatty", "", "router is object:", u.isObject(e));
490
+ K.Log("Koatty", "", "router has LoadRouter:", u.isFunction(e === null || e === void 0 ? void 0 : e.LoadRouter));
491
+ K.Log("Koatty", "", "Controllers to load:", t);
492
+ if (u.isObject(e) && !u.isFunction(e.LoadRouter)) {
493
+ const a = e;
494
+ K.Log("Koatty", "", `Multi-protocol routing: found ${Object.keys(a).length} routers (${Object.keys(a).join(", ")})`);
495
+ for (const e in a) {
496
+ K.Log("Koatty", "", `Checking protocol: ${e}, has LoadRouter:`, u.isFunction((o = a[e]) === null || o === void 0 ? void 0 : o.LoadRouter));
497
+ if (a[e] && u.isFunction(a[e].LoadRouter)) {
498
+ K.Log("Koatty", "", `Loading routes for protocol: ${e}`);
499
+ await a[e].LoadRouter(this.app, t);
500
+ K.Log("Koatty", "", `Completed loading routes for protocol: ${e}`);
501
+ }
502
+ }
503
+ } else if (u.isFunction(e.LoadRouter)) {
504
+ K.Log("Koatty", "", "Single protocol routing");
505
+ await e.LoadRouter(this.app, t);
506
+ } else K.Warn("No valid router found! router:", e);
507
+ K.Log("Koatty", "", "============ LoadRouter END ============");
390
508
  }
391
509
  }
392
510
 
@@ -398,87 +516,110 @@ class Loader {
398
516
  * @LastEditTime: 2025-01-14 16:11:21
399
517
  * @License: BSD (3-Clause)
400
518
  * @Copyright (c): <richenlin(at)gmail.com>
401
- */ function _(t) {
402
- return function(e) {
403
- if (!(e.prototype instanceof p)) throw new Error(`class does not inherit from Koatty`);
404
- b(e, t);
519
+ */ function T(t) {
520
+ return function(o) {
521
+ if (!(o.prototype instanceof g)) throw new Error(`class does not inherit from Koatty`);
522
+ x(o, t);
523
+ return o;
405
524
  };
406
525
  }
407
526
 
408
- function O(t) {
409
- return async e => {
410
- if (!(e.prototype instanceof p)) throw new Error(`class ${e.name} does not inherit from Koatty`);
411
- return await b(e, t, !0);
527
+ function _(t) {
528
+ return async o => {
529
+ if (!(o.prototype instanceof g)) throw new Error(`class ${o.name} does not inherit from Koatty`);
530
+ return await x(o, t, !0);
412
531
  };
413
532
  }
414
533
 
415
- function S(t) {
534
+ function F(t) {
416
535
  return a => {
417
- if (!(a.prototype instanceof p)) throw new Error(`class does not inherit from Koatty`);
536
+ if (!(a.prototype instanceof g)) throw new Error(`class does not inherit from Koatty`);
418
537
  t = t !== null && t !== void 0 ? t : "";
419
- e.saveClassMetadata(o, R, t, a);
538
+ o.saveClassMetadata(e, k, t, a);
420
539
  };
421
540
  }
422
541
 
423
- function I(t) {
542
+ function N(t) {
424
543
  return a => {
425
- if (!(a.prototype instanceof p)) throw new Error(`class does not inherit from Koatty`);
544
+ if (!(a.prototype instanceof g)) throw new Error(`class does not inherit from Koatty`);
426
545
  t = t !== null && t !== void 0 ? t : "";
427
- e.saveClassMetadata(o, k, t, a);
546
+ o.saveClassMetadata(e, $, t, a);
428
547
  };
429
548
  }
430
549
 
431
- function K(t, a, s) {
432
- e.attachClassMetadata(o, t, a, s);
550
+ function I(t, a, r) {
551
+ o.attachClassMetadata(e, t, a, r);
433
552
  }
434
553
 
435
- const b = async function(t, o, a = !1) {
436
- M();
437
- const s = $();
438
- if (!a && s) return;
439
- const r = Reflect.construct(t, []);
554
+ const x = async function(t, e, r = !1) {
555
+ S();
556
+ const s = A();
557
+ if (!r && s) return;
558
+ const n = Reflect.construct(t, []);
440
559
  if (s) {
441
- r.silent = !0;
442
- w.enable(!1);
560
+ n.silent = !0;
561
+ K.enable(!1);
443
562
  }
444
563
  try {
445
- if (!r.silent) w.Log("Koatty", T);
446
- if (!(r instanceof p)) throw new Error(`class ${t.name} does not inherit from Koatty`);
447
- Loader.initialize(r);
448
- if (f.isFunction(o)) {
449
- w.Log("Koatty", "", "Execute bootFunc ...");
450
- await o(r);
564
+ if (!n.silent) console.log(O);
565
+ if (!(n instanceof g)) throw new Error(`class ${t.name} does not inherit from Koatty`);
566
+ Loader.initialize(n);
567
+ if (u.isFunction(e)) {
568
+ K.Log("Koatty", "", "Execute bootFunc ...");
569
+ await e(n);
451
570
  }
452
- e.setApp(r);
453
- w.Log("Koatty", "", "ComponentScan ...");
454
- Loader.CheckAllComponents(r, t);
455
- Loader.LoadAppEventHooks(r, t);
456
- w.Log("Koatty", "", "Emit App Boot ...");
457
- await d(r, "appBoot");
458
- await Loader.LoadAllComponents(r, t);
459
- w.Log("Koatty", "", "Emit App Ready ...");
460
- await d(r, "appReady");
461
- if (!s) r.listen(N);
462
- return r;
571
+ o.setApp(n);
572
+ K.Log("Koatty", "", "ComponentScan ...");
573
+ Loader.CheckAllComponents(n, t);
574
+ Loader.LoadAppEventHooks(n, t);
575
+ K.Log("Koatty", "", "Emit App Boot ...");
576
+ await i(n, a.appBoot);
577
+ await Loader.LoadAllComponents(n, t);
578
+ K.Log("Koatty", "", "Emit App Ready ...");
579
+ await i(n, a.appReady);
580
+ if (!s) {
581
+ K.Log("Koatty", "", "Emit Before Server Start ...");
582
+ await i(n, a.beforeServerStart);
583
+ n.listen(D);
584
+ K.Log("Koatty", "", "Emit After Server Start ...");
585
+ await i(n, a.afterServerStart);
586
+ }
587
+ return n;
463
588
  } catch (t) {
464
- w.Error(t);
465
- process.exit();
589
+ K.Fatal(t);
590
+ process.exit(1);
466
591
  }
467
592
  };
468
593
 
469
- const N = t => {
470
- let e = [];
471
- if (!Array.isArray(t.server)) e = [ t.server ]; else e = t.server;
472
- w.Log("Koatty", "", "====================================");
473
- w.Log("Koatty", "", `Nodejs Version: ${process.version}`);
474
- w.Log("Koatty", "", `Koatty Version: v${E}`);
475
- w.Log("Koatty", "", `App Environment: ${t.env}`);
476
- e.forEach((t => {
477
- w.Log("Koatty", "", `Server: ${t.options.protocol.toUpperCase()} running at ${t.options.protocol === "http2" ? "https" : t.options.protocol}://${t.options.hostname || "127.0.0.1"}:${t.options.port}/`);
478
- }));
479
- w.Log("Koatty", "", "====================================");
480
- if (t.appDebug) w.Warn(`Running in debug mode.`);
481
- Loader.SetLogger(t);
594
+ const D = t => {
595
+ K.Log("Koatty", "", "====================================");
596
+ K.Log("Koatty", "", `Nodejs Version: ${process.version}`);
597
+ K.Log("Koatty", "", `Koatty Version: v${b}`);
598
+ K.Log("Koatty", "", `App Environment: ${t.env}`);
599
+ if (t.appDebug) K.Warn(`Running in debug mode.`);
600
+ K.Log("Koatty", "", "====================================");
482
601
  };
483
602
 
484
- export { K as BindEventHook, _ as Bootstrap, S as ComponentScan, I as ConfigurationScan, O as ExecBootStrap, w as Logger };
603
+ /*
604
+ * @Description: framework main file
605
+ * @Usage:
606
+ * @Author: richen
607
+ * @Date: 2023-12-09 21:56:32
608
+ * @LastEditTime: 2025-01-14 16:12:41
609
+ * @License: BSD (3-Clause)
610
+ * @Copyright (c): <richenlin(at)gmail.com>
611
+ */ function B() {
612
+ try {
613
+ require("koatty_router/dist/RouterPlugin");
614
+ } catch (t) {}
615
+ try {
616
+ require("koatty_serve/dist/ServePlugin");
617
+ } catch (t) {}
618
+ try {
619
+ require("koatty_trace/dist/TracePlugin");
620
+ } catch (t) {}
621
+ }
622
+
623
+ B();
624
+
625
+ export { I as BindEventHook, T as Bootstrap, F as ComponentScan, N as ConfigurationScan, _ as ExecBootStrap, K as Logger };