alemonjs 2.1.0-alpha.45 → 2.1.0-alpha.47

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/lib/adapter.js CHANGED
@@ -109,14 +109,5 @@ function startAdapterWithFallback() {
109
109
  };
110
110
  startByFork();
111
111
  }
112
- ['SIGINT', 'SIGTERM', 'SIGQUIT', 'disconnect'].forEach(sig => {
113
- process?.on?.(sig, () => {
114
- logger?.info?.(`[${sig}] 收到信号,正在关闭...`);
115
- setImmediate(() => process.exit(0));
116
- });
117
- });
118
- process?.on?.('exit', (code) => {
119
- logger?.info?.(`[exit] 进程退出,code=${code}`);
120
- });
121
112
 
122
113
  export { startAdapterWithFallback };
@@ -0,0 +1,11 @@
1
+ import { DefineResponseFunc } from '../types/event/index.js';
2
+
3
+ /**
4
+ * Lazy load a response handler
5
+ * @param fnc
6
+ * @returns
7
+ */
8
+ declare const lazy: (fnc: () => Promise<any>) => () => Promise<any>;
9
+ declare const defineResponse: DefineResponseFunc;
10
+
11
+ export { defineResponse, lazy };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Lazy load a response handler
3
+ * @param fnc
4
+ * @returns
5
+ */
6
+ const lazy = (fnc) => {
7
+ return async () => (await fnc()).default;
8
+ };
9
+ const defineResponse = (responses) => {
10
+ return {
11
+ current: responses
12
+ };
13
+ };
14
+ global.defineResponse = defineResponse;
15
+
16
+ export { defineResponse, lazy };
@@ -0,0 +1,75 @@
1
+ import { isAsyncFunction } from 'util/types';
2
+ import 'fs';
3
+ import 'path';
4
+ import 'yaml';
5
+ import { showErrorModule } from '../core/utils.js';
6
+ import { useMessage } from './hook-use-api.js';
7
+
8
+ const createCallHandler = (valueEvent) => {
9
+ const [message] = useMessage(valueEvent);
10
+ // 开始处理 heandler
11
+ const callHandler = (currents, nextEvent) => {
12
+ let index = 0;
13
+ let isClose = false;
14
+ let isNext = false;
15
+ const onRes = (res) => {
16
+ if (!res) {
17
+ isClose = true;
18
+ return;
19
+ }
20
+ if (Array.isArray(res)) {
21
+ if (res.length > 0) {
22
+ // 发送数据
23
+ void message.send(res);
24
+ }
25
+ isClose = true;
26
+ }
27
+ else if (typeof res === 'object') {
28
+ if (Array.isArray(res.data)) {
29
+ // 发送数据
30
+ void message.send(res.data);
31
+ }
32
+ if (!res.allowGrouping) {
33
+ isClose = true;
34
+ }
35
+ }
36
+ };
37
+ const start = async () => {
38
+ if (index >= currents.length) {
39
+ return;
40
+ }
41
+ if (isNext) {
42
+ return;
43
+ }
44
+ if (isClose) {
45
+ return;
46
+ }
47
+ try {
48
+ if (isAsyncFunction(currents[index])) {
49
+ const res = await currents[index](valueEvent, (...cns) => {
50
+ isNext = true;
51
+ nextEvent(...cns);
52
+ });
53
+ onRes(res);
54
+ }
55
+ else {
56
+ const res = currents[index](valueEvent, (...cns) => {
57
+ isNext = true;
58
+ nextEvent(...cns);
59
+ });
60
+ onRes(res);
61
+ }
62
+ }
63
+ catch (err) {
64
+ showErrorModule(err);
65
+ return;
66
+ }
67
+ ++index;
68
+ void start();
69
+ };
70
+ void start();
71
+ };
72
+ return callHandler;
73
+ };
74
+
75
+ export { createCallHandler };
@@ -0,0 +1,100 @@
1
+ import { isAsyncFunction } from 'util/types';
2
+ import { ResponseRouter } from './store.js';
3
+ import { EventMessageText } from '../core/variable.js';
4
+ import 'fs';
5
+ import 'path';
6
+ import 'yaml';
7
+ import { showErrorModule } from '../core/utils.js';
8
+ import { createCallHandler } from './event-processor-event-callHandler.js';
9
+
10
+ /**
11
+ * @fileoverview 消息处理快
12
+ * 登录模块向核心模块发送数据
13
+ * 核心模块调用模块索引
14
+ * @module processor
15
+ * @author ningmengchongshui
16
+ */
17
+ const expendEventRoute = (valueEvent, select, nextCycle) => {
18
+ const resRoute = new ResponseRouter();
19
+ const routes = resRoute.value;
20
+ // 开始处理 heandler
21
+ const callHandler = createCallHandler(valueEvent);
22
+ // 开始处理 handler
23
+ const processChildren = (nodes, middleware, next) => {
24
+ if (!nodes || nodes.length === 0) {
25
+ next();
26
+ return;
27
+ }
28
+ let idx = 0;
29
+ const nextNode = async () => {
30
+ idx++;
31
+ if (idx > nodes.length) {
32
+ next();
33
+ return;
34
+ }
35
+ const node = nodes[idx - 1];
36
+ // 正则匹配
37
+ if (EventMessageText.includes(select) && node.regular) {
38
+ const reg = new RegExp(node.regular);
39
+ if (!reg.test(valueEvent['MessageText'])) {
40
+ void nextNode();
41
+ return;
42
+ }
43
+ }
44
+ if (!node.handler) {
45
+ void nextNode();
46
+ return;
47
+ }
48
+ // 递归:如果有children,继续递归下去
49
+ if (node.children && node.children.length > 0) {
50
+ // middleware 追加自身 handler
51
+ processChildren(node.children, [...middleware, node.handler], nextNode);
52
+ return;
53
+ }
54
+ // 没有children,直接处理handler
55
+ const currentsAndMiddleware = [...middleware, node.handler];
56
+ // node.handler 是一个异步函数。函数执行的结果是 { current: Current[] | Current, select: xxx }
57
+ try {
58
+ const currents = [];
59
+ for (const item of currentsAndMiddleware) {
60
+ const app = isAsyncFunction(item) ? (await item()) : item();
61
+ // 没有 default。因为是 import x from './';
62
+ // 中间件也有 selects。
63
+ // 如果 发现 和当前要处理的 selects 不匹配。
64
+ // 只要是一个不匹配。则说明处理还不是最终想要执行结果。
65
+ const selects = Array.isArray(app.select) ? app.select : [app.select];
66
+ // 没有匹配到
67
+ if (!selects.includes(select)) {
68
+ // 需要继续。
69
+ void nextNode();
70
+ return;
71
+ }
72
+ // 可能是数组。也可能不是数组
73
+ const currentsItem = Array.isArray(app.current) ? app.current : [app.current];
74
+ currents.push(...currentsItem);
75
+ }
76
+ // 要把二维数组拍平
77
+ callHandler(currents, (cn, ...cns) => {
78
+ if (cn) {
79
+ // 这里的 next 要加 true。
80
+ // 因为下一层是旧版本逻辑。不加一层。会出现处理了没有完全结束周期
81
+ nextCycle(true, ...cns);
82
+ return;
83
+ }
84
+ void nextNode();
85
+ });
86
+ }
87
+ catch (err) {
88
+ showErrorModule(err);
89
+ }
90
+ };
91
+ void nextNode();
92
+ };
93
+ if (routes.length === 0) {
94
+ nextCycle();
95
+ return;
96
+ }
97
+ void processChildren(routes, [], nextCycle);
98
+ };
99
+
100
+ export { expendEventRoute };
@@ -1,6 +1,14 @@
1
1
  import { Next } from '../types/cycle/index.js';
2
2
  import { EventKeys, Events } from '../types/event/map.js';
3
3
 
4
+ /**
5
+ * @fileoverview 消息处理快
6
+ * 登录模块向核心模块发送数据
7
+ * 核心模块调用模块索引
8
+ * @module processor
9
+ * @author ningmengchongshui
10
+ */
11
+
4
12
  /**
5
13
  * 消息体处理机制
6
14
  * @param event
@@ -1,17 +1,10 @@
1
- import { isAsyncFunction } from 'util/types';
2
1
  import { useState } from './hook-use-state.js';
3
2
  import { showErrorModule } from '../core/utils.js';
4
3
  import { Response } from './store.js';
5
- import { useMessage } from './hook-use-api.js';
6
4
  import { EventMessageText } from '../core/variable.js';
5
+ import { expendEventRoute } from './event-processor-event-route.js';
6
+ import { createCallHandler } from './event-processor-event-callHandler.js';
7
7
 
8
- /**
9
- * @fileoverview 消息处理快
10
- * 登录模块向核心模块发送数据
11
- * 核心模块调用模块索引
12
- * @module processor
13
- * @author ningmengchongshui
14
- */
15
8
  /**
16
9
  * 消息体处理机制
17
10
  * @param event
@@ -19,10 +12,11 @@ import { EventMessageText } from '../core/variable.js';
19
12
  */
20
13
  const expendEvent = (valueEvent, select, next) => {
21
14
  const res = new Response();
22
- const [message] = useMessage(valueEvent);
23
- // 得到所有 res
15
+ // 得到所有 response
24
16
  const StoreResponse = res.value;
25
17
  let valueI = 0;
18
+ // 开始处理 heandler
19
+ const callHandler = createCallHandler(valueEvent);
26
20
  /**
27
21
  * 下一步
28
22
  * @returns
@@ -94,65 +88,14 @@ const expendEvent = (valueEvent, select, next) => {
94
88
  }
95
89
  }
96
90
  const currents = Array.isArray(app.default.current) ? app.default.current : [app.default.current];
97
- let index = 0;
98
- let isClose = false;
99
- let isNext = false;
100
- const onRes = (res) => {
101
- if (!res) {
102
- isClose = true;
103
- return;
104
- }
105
- if (Array.isArray(res)) {
106
- if (res.length > 0) {
107
- // 发送数据
108
- void message.send(res);
109
- }
110
- isClose = true;
111
- }
112
- else if (typeof res === 'object') {
113
- if (Array.isArray(res.data)) {
114
- // 发送数据
115
- void message.send(res.data);
116
- }
117
- if (!res.allowGrouping) {
118
- isClose = true;
119
- }
120
- }
121
- };
122
- const start = async () => {
123
- if (index >= currents.length) {
124
- return;
125
- }
126
- if (isNext) {
127
- return;
128
- }
129
- if (isClose) {
130
- return;
131
- }
132
- if (isAsyncFunction(currents[index])) {
133
- const res = await currents[index](valueEvent, (...cns) => {
134
- isNext = true;
135
- nextEvent(...cns);
136
- });
137
- onRes(res);
138
- }
139
- else {
140
- const res = currents[index](valueEvent, (...cns) => {
141
- isNext = true;
142
- nextEvent(...cns);
143
- });
144
- onRes(res);
145
- }
146
- ++index;
147
- void start();
148
- };
149
- void start();
91
+ callHandler(currents, nextEvent);
150
92
  }
151
93
  catch (err) {
152
94
  showErrorModule(err);
153
95
  }
154
96
  };
155
- nextEvent();
97
+ // 路由优先。路由的搞完了。再处理其他
98
+ expendEventRoute(valueEvent, select, nextEvent);
156
99
  };
157
100
 
158
101
  export { expendEvent };
@@ -1,6 +1,6 @@
1
- import { EventKeys, Events } from '../types/event/map.js';
2
- import { User } from '../types/event/base/user.js';
3
1
  import { Result } from '../core/utils.js';
2
+ import { User } from '../types/event/base/user.js';
3
+ import { EventKeys, Events } from '../types/event/map.js';
4
4
  import { DataEnums } from '../types/message/index.js';
5
5
 
6
6
  type Options = {
package/lib/app/load.d.ts CHANGED
@@ -9,6 +9,6 @@ declare const loadChildren: (mainPath: string, appName: string) => Promise<void>
9
9
  * 模块文件
10
10
  * @param app
11
11
  */
12
- declare const loadChildrenFile: (appName: string) => Promise<void>;
12
+ declare const loadChildrenFile: (appName: string) => void;
13
13
 
14
14
  export { loadChildren, loadChildrenFile };
package/lib/app/load.js CHANGED
@@ -50,7 +50,9 @@ const loadChildren = async (mainPath, appName) => {
50
50
  // 卸载
51
51
  App.un();
52
52
  try {
53
- app?.unMounted && (await app.unMounted(e));
53
+ if (app?.unMounted) {
54
+ await app.unMounted(e);
55
+ }
54
56
  }
55
57
  catch (e) {
56
58
  // 卸载周期出意外,不需要进行卸载
@@ -59,18 +61,37 @@ const loadChildren = async (mainPath, appName) => {
59
61
  };
60
62
  // onCreated 创建
61
63
  try {
62
- app?.onCreated && (await app?.onCreated());
64
+ if (app?.onCreated) {
65
+ await app?.onCreated();
66
+ }
63
67
  }
64
68
  catch (e) {
65
- unMounted(e);
69
+ void unMounted(e);
66
70
  // 出错了,结束后续的操作。
67
71
  return;
68
72
  }
69
- // onMounted 加载
70
- try {
71
- /**
72
- * load response files
73
- */
73
+ const registerMounted = async () => {
74
+ const res = await app?.register();
75
+ if (res && res?.response) {
76
+ // 注册了 response
77
+ // 使用新的模式去进行回调执行。
78
+ // 不再需要用文件import的方式去加载。
79
+ App.register(res);
80
+ }
81
+ // 加载完成
82
+ App.on();
83
+ // mounted
84
+ try {
85
+ if (app?.onMounted) {
86
+ await app.onMounted({ response: [], middleware: [] });
87
+ }
88
+ }
89
+ catch (e) {
90
+ void unMounted(e);
91
+ }
92
+ ;
93
+ };
94
+ const fileMounted = async () => {
74
95
  const appsDir = join(mainDir, 'apps');
75
96
  const appsFiles = getRecursiveDirFiles(appsDir);
76
97
  // 使用 新 目录 response
@@ -114,13 +135,28 @@ const loadChildren = async (mainPath, appName) => {
114
135
  mwData.push(middleware);
115
136
  }
116
137
  App.pushMiddleware(mwData);
138
+ // 加载完成
117
139
  App.on();
140
+ // mounted
118
141
  try {
119
- app?.onMounted && (await app.onMounted({ response: resData, middleware: mwData }));
142
+ if (app?.onMounted) {
143
+ await app.onMounted({ response: resData, middleware: mwData });
144
+ }
120
145
  }
121
146
  catch (e) {
122
147
  void unMounted(e);
123
148
  }
149
+ };
150
+ // onMounted 加载
151
+ try {
152
+ if (app?.register) {
153
+ // 优先使用 register
154
+ await registerMounted();
155
+ }
156
+ else {
157
+ // 使用文件方式加载
158
+ await fileMounted();
159
+ }
124
160
  }
125
161
  catch (e) {
126
162
  void unMounted(e);
@@ -137,7 +173,7 @@ const loadChildren = async (mainPath, appName) => {
137
173
  * 模块文件
138
174
  * @param app
139
175
  */
140
- const loadChildrenFile = async (appName) => {
176
+ const loadChildrenFile = (appName) => {
141
177
  if (typeof appName !== 'string') {
142
178
  logger.error({
143
179
  code: ResultCode.FailParams,
@@ -1,4 +1,5 @@
1
1
  import { EventCycleEnum, ChildrenCycle } from '../types/cycle/index.js';
2
+ import { ResponseRoute, childrenCallbackRes } from '../types/event/index.js';
2
3
  import { EventKeys } from '../types/event/map.js';
3
4
  import { StoreChildrenApp, StoreResponseItem, StoreMiddlewareItem } from '../types/store/res.js';
4
5
  import { StateSubscribeMap, SubscribeKeysMap, SubscribeValue } from '../types/subscribe/index.js';
@@ -29,6 +30,9 @@ declare class Core {
29
30
  declare class Response {
30
31
  get value(): StoreResponseItem[];
31
32
  }
33
+ declare class ResponseRouter {
34
+ get value(): ResponseRoute[];
35
+ }
32
36
  declare class Middleware {
33
37
  get value(): StoreMiddlewareItem[];
34
38
  }
@@ -58,6 +62,7 @@ declare class State {
58
62
  declare class ChildrenApp {
59
63
  #private;
60
64
  constructor(name?: string);
65
+ register(config: childrenCallbackRes): void;
61
66
  /**
62
67
  * 推送响应体
63
68
  * @param data
@@ -89,4 +94,4 @@ declare class ChildrenApp {
89
94
  declare const ProcessorEventAutoClearMap: Map<any, any>;
90
95
  declare const ProcessorEventUserAudoClearMap: Map<any, any>;
91
96
 
92
- export { ChildrenApp, Core, Logger, Middleware, ProcessorEventAutoClearMap, ProcessorEventUserAudoClearMap, Response, State, StateSubscribe, SubscribeList };
97
+ export { ChildrenApp, Core, Logger, Middleware, ProcessorEventAutoClearMap, ProcessorEventUserAudoClearMap, Response, ResponseRouter, State, StateSubscribe, SubscribeList };
package/lib/app/store.js CHANGED
@@ -135,6 +135,14 @@ class Response {
135
135
  return data.flat();
136
136
  }
137
137
  }
138
+ class ResponseRouter {
139
+ get value() {
140
+ const data = Object.keys(alemonjsCore.storeChildrenApp).map(key => {
141
+ return alemonjsCore.storeChildrenApp[key].register?.response?.current ?? [];
142
+ });
143
+ return data.flat();
144
+ }
145
+ }
138
146
  class Middleware {
139
147
  get value() {
140
148
  // 得到所有 app,得到所有 res
@@ -235,6 +243,10 @@ class ChildrenApp {
235
243
  constructor(name = 'main') {
236
244
  this.#name = name;
237
245
  }
246
+ #registerRes = {};
247
+ register(config) {
248
+ this.#registerRes = config;
249
+ }
238
250
  /**
239
251
  * 推送响应体
240
252
  * @param data
@@ -264,7 +276,8 @@ class ChildrenApp {
264
276
  name: this.#name,
265
277
  middleware: this.#middleware,
266
278
  response: this.#response,
267
- cycle: this.#cycle
279
+ cycle: this.#cycle,
280
+ register: this.#registerRes
268
281
  };
269
282
  }
270
283
  /**
@@ -287,4 +300,4 @@ class ChildrenApp {
287
300
  const ProcessorEventAutoClearMap = new Map();
288
301
  const ProcessorEventUserAudoClearMap = new Map();
289
302
 
290
- export { ChildrenApp, Core, Logger, Middleware, ProcessorEventAutoClearMap, ProcessorEventUserAudoClearMap, Response, State, StateSubscribe, SubscribeList };
303
+ export { ChildrenApp, Core, Logger, Middleware, ProcessorEventAutoClearMap, ProcessorEventUserAudoClearMap, Response, ResponseRouter, State, StateSubscribe, SubscribeList };
@@ -0,0 +1,51 @@
1
+ import { existsSync } from 'fs';
2
+ import path, { dirname } from 'path';
3
+
4
+ /**
5
+ * 递归向上查找所有目录级 _middleware 文件
6
+ * 支持 .ts/.js/.cjs/.mjs/.tsx/.jsx
7
+ * 按目录从上到下顺序合成
8
+ */
9
+ async function collectMiddlewares(routeFile) {
10
+ const middlewares = [];
11
+ let dir = dirname(routeFile);
12
+ // 支持的后缀
13
+ const suffixes = ['.ts', '.js', '.cjs', '.mjs', '.tsx', '.jsx'];
14
+ while (true) {
15
+ for (const ext of suffixes) {
16
+ const mwPath = path.join(dir, `_middleware${ext}`);
17
+ if (existsSync(mwPath)) {
18
+ const mw = (await import(`file://${mwPath}`)).default;
19
+ if (typeof mw === 'function') {
20
+ middlewares.unshift(mw);
21
+ }
22
+ }
23
+ }
24
+ const parent = dirname(dir);
25
+ if (parent === dir) {
26
+ break;
27
+ }
28
+ dir = parent;
29
+ }
30
+ return middlewares;
31
+ }
32
+ /**
33
+ * 依次执行中间件链,最后执行 handler
34
+ * 如果有任意中间件或 handler 抛错,自动捕获并处理
35
+ */
36
+ async function runMiddlewares(middlewares, ctx, handler) {
37
+ let idx = 0;
38
+ async function dispatch() {
39
+ if (idx < middlewares.length) {
40
+ // 执行下一个中间件
41
+ await middlewares[idx++](ctx, dispatch);
42
+ }
43
+ else {
44
+ // 执行最终 handler
45
+ await handler(ctx);
46
+ }
47
+ }
48
+ await dispatch();
49
+ }
50
+
51
+ export { collectMiddlewares, runMiddlewares };
@@ -0,0 +1,40 @@
1
+ import fs, { existsSync } from 'fs';
2
+
3
+ // 输入一个文件路径。
4
+ const getModuelFile = (dir) => {
5
+ const dirMap = {
6
+ '.js': `${dir}.js`,
7
+ '.jsx': `${dir}.jsx`,
8
+ '.mjs': `${dir}.mjs`,
9
+ '.cjs': `${dir}.cjs`,
10
+ '/index.js': `${dir}/index.js`,
11
+ '/index.jsx': `${dir}/index.jsx`,
12
+ '/index.mjs': `${dir}/index.mjs`,
13
+ '/index.cjs': `${dir}/index.cjs`,
14
+ '.ts': `${dir}.ts`,
15
+ '.tsx': `${dir}.tsx`,
16
+ '/index.ts': `${dir}/index.ts`,
17
+ '/index.tsx': `${dir}/index.tsx`
18
+ };
19
+ for (const key in dirMap) {
20
+ const filePath = dirMap[key];
21
+ if (existsSync(filePath) && fs.statSync(filePath)) {
22
+ return filePath;
23
+ }
24
+ }
25
+ return '';
26
+ };
27
+ const formatPath = (path) => {
28
+ if (!path || path === '/') {
29
+ return '/index.html';
30
+ }
31
+ const pates = path.split('/');
32
+ const lastPath = pates[pates.length - 1];
33
+ if (lastPath.includes('.')) {
34
+ return path;
35
+ }
36
+ path += '.html';
37
+ return path;
38
+ };
39
+
40
+ export { formatPath, getModuelFile };
package/lib/cbp/router.js CHANGED
@@ -4,45 +4,11 @@ import path, { join, dirname } from 'path';
4
4
  import mime from 'mime-types';
5
5
  import { createRequire } from 'module';
6
6
  import { html } from './hello.html.js';
7
+ import { getModuelFile, formatPath } from './router-utils.js';
8
+ import { collectMiddlewares, runMiddlewares } from './router-middleware.js';
7
9
 
8
10
  const require = createRequire(import.meta.url);
9
11
  const mainDirMap = new Map();
10
- const formatPath = (path) => {
11
- if (!path || path === '/') {
12
- return '/index.html';
13
- }
14
- const pates = path.split('/');
15
- const lastPath = pates[pates.length - 1];
16
- if (lastPath.includes('.')) {
17
- return path;
18
- }
19
- path += '.html';
20
- return path;
21
- };
22
- // 输入一个文件路径。
23
- const getModuelFile = (dir) => {
24
- const dirMap = {
25
- '.js': `${dir}.js`,
26
- '.jsx': `${dir}.jsx`,
27
- '.mjs': `${dir}.mjs`,
28
- '.cjs': `${dir}.cjs`,
29
- '/index.js': `${dir}/index.js`,
30
- '/index.jsx': `${dir}/index.jsx`,
31
- '/index.mjs': `${dir}/index.mjs`,
32
- '/index.cjs': `${dir}/index.cjs`,
33
- '.ts': `${dir}.ts`,
34
- '.tsx': `${dir}.tsx`,
35
- '/index.ts': `${dir}/index.ts`,
36
- '/index.tsx': `${dir}/index.tsx`
37
- };
38
- for (const key in dirMap) {
39
- const filePath = dirMap[key];
40
- if (existsSync(filePath) && fs.statSync(filePath)) {
41
- return filePath;
42
- }
43
- }
44
- return '';
45
- };
46
12
  const router = new KoaRouter({
47
13
  prefix: '/'
48
14
  });
@@ -109,11 +75,13 @@ router.all('app/{*path}', async (ctx) => {
109
75
  return;
110
76
  }
111
77
  const apiModule = await import(`file://${modulePath}`);
112
- if (!apiModule[ctx.method] || typeof apiModule[ctx.method] !== 'function') {
78
+ const handler = apiModule[ctx.method];
79
+ if (!handler || typeof handler !== 'function') {
113
80
  ctx.status = 405;
114
81
  return;
115
82
  }
116
- await apiModule[ctx.method](ctx);
83
+ const middlewares = await collectMiddlewares(modulePath);
84
+ await runMiddlewares(middlewares, ctx, handler);
117
85
  }
118
86
  catch (err) {
119
87
  console.error(`Error handling API request ${ctx.path}`);
@@ -214,17 +182,19 @@ router.all('apps/:app/{*path}', async (ctx) => {
214
182
  ctx.status = 404;
215
183
  ctx.body = {
216
184
  code: 404,
217
- message: `API 'route/${ctx.path}' 未找到。`,
218
- data: null
185
+ message: `API '${ctx.path}' 未找到。`,
186
+ data: 'existsSync modulePath'
219
187
  };
220
188
  return;
221
189
  }
222
190
  const apiModule = await import(`file://${modulePath}`);
223
- if (!apiModule[ctx.method] || typeof apiModule[ctx.method] !== 'function') {
191
+ const handler = apiModule[ctx.method];
192
+ if (!handler || typeof handler !== 'function') {
224
193
  ctx.status = 405;
225
194
  return;
226
195
  }
227
- await apiModule[ctx.method](ctx);
196
+ const middlewares = await collectMiddlewares(modulePath);
197
+ await runMiddlewares(middlewares, ctx, handler);
228
198
  }
229
199
  catch (err) {
230
200
  logger.warn(`Error request ${ctx.path}:`, err?.message || '');
package/lib/global.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { OnResponseReversalFunc, OnResponseReversalFuncBack, OnMiddlewareReversalFunc, OnMiddlewareReversalFuncBack, DefineChildrenFunc, OnSelectsFunc, OnDataFormatFunc, OnGroupFunc } from './types/event/index.js';
1
+ import { OnResponseReversalFunc, OnResponseReversalFuncBack, OnMiddlewareReversalFunc, OnMiddlewareReversalFuncBack, DefineChildrenFunc, DefineResponseFunc, OnSelectsFunc, OnDataFormatFunc, OnGroupFunc } from './types/event/index.js';
2
2
  import { StoreChildrenApp } from './types/store/res.js';
3
3
  import { StateSubscribeMap, SubscribeKeysMap } from './types/subscribe/index.js';
4
4
  import { LoggerUtils } from './types/logger/index.js';
@@ -62,6 +62,10 @@ declare global {
62
62
  * 定义一个子模块
63
63
  */
64
64
  var defineChildren: DefineChildrenFunc;
65
+ /**
66
+ * 定义响应体
67
+ */
68
+ var defineResponse: DefineResponseFunc;
65
69
  /**
66
70
  * 定义选择器
67
71
  */
package/lib/index.d.ts CHANGED
@@ -11,7 +11,7 @@ export { PublicEventMessageCreate, PublicEventMessageDelete, PublicEventMessageR
11
11
  export { PrivateEventMessageCreate, PrivateEventMessageDelete, PrivateEventMessageUpdate } from './types/event/message/private.message.js';
12
12
  export { PrivateEventRequestFriendAdd, PrivateEventRequestGuildAdd } from './types/event/request/index.js';
13
13
  export { ActionsEventEnum } from './types/event/actions.js';
14
- export { Current, CurrentResult, CurrentResultValue, DefineChildrenCallback, DefineChildrenFunc, DefineChildrenValue, DefinePlatformCallback, DefinePlatformFunc, DefinePlatformValue, OnDataFormatFunc, OnGroupFunc, OnGroupItem, OnMiddlewareFunc, OnMiddlewareReversalFunc, OnMiddlewareReversalFuncBack, OnMiddlewareValue, OnResponseFunc, OnResponseReversalFunc, OnResponseReversalFuncBack, OnResponseValue, OnSelectsFunc } from './types/event/index.js';
14
+ export { Current, CurrentResult, CurrentResultValue, DefineChildrenCallback, DefineChildrenFunc, DefineChildrenValue, DefinePlatformCallback, DefinePlatformFunc, DefinePlatformValue, DefineResponseFunc, OnDataFormatFunc, OnGroupFunc, OnGroupItem, OnMiddlewareFunc, OnMiddlewareReversalFunc, OnMiddlewareReversalFuncBack, OnMiddlewareValue, OnResponseFunc, OnResponseReversalFunc, OnResponseReversalFuncBack, OnResponseValue, OnSelectsFunc, ResponseRoute, childrenCallback, childrenCallbackRes } from './types/event/index.js';
15
15
  export { EventKeys, Events, EventsEnum, EventsMessageCreate, EventsMessageCreateEnum, EventsMessageCreateKeys } from './types/event/map.js';
16
16
  export { LoggerUtils } from './types/logger/index.js';
17
17
  export { ClientAPI, ClientAPIMessageResult } from './types/client/index.js';
@@ -20,6 +20,7 @@ export { StoreChildrenApp, StoreMiddleware, StoreMiddlewareItem, StoreResponse,
20
20
  export { StateSubscribeMap, SubscribeKeysMap, SubscribeMap, SubscribeValue } from './types/subscribe/index.js';
21
21
  export { core, logger } from './global.js';
22
22
  export { defineChildren } from './app/define-chidren.js';
23
+ export { defineResponse, lazy } from './app/define-response.js';
23
24
  export { onGroup } from './app/event-group.js';
24
25
  export { OnMiddleware, onMiddleware } from './app/event-middleware.js';
25
26
  export { OnProcessor, onProcessor } from './app/event-processor.js';
@@ -34,7 +35,7 @@ export { useObserver, useSubscribe } from './app/hook-use-subscribe.js';
34
35
  export { loadChildren, loadChildrenFile } from './app/load.js';
35
36
  export { createDataFormat, createEventValue, format, sendToChannel, sendToUser } from './app/message-api.js';
36
37
  export { Ark, BT, Image, ImageFile, ImageURL, Link, MD, Mention, Text } from './app/message-format.js';
37
- export { ChildrenApp, Core, Logger, Middleware, ProcessorEventAutoClearMap, ProcessorEventUserAudoClearMap, Response, State, StateSubscribe, SubscribeList } from './app/store.js';
38
+ export { ChildrenApp, Core, Logger, Middleware, ProcessorEventAutoClearMap, ProcessorEventUserAudoClearMap, Response, ResponseRouter, State, StateSubscribe, SubscribeList } from './app/store.js';
38
39
  export { ResultCode } from './core/variable.js';
39
40
  export { ConfigCore, getConfig, getConfigValue } from './core/config.js';
40
41
  export { Result, createEventName, createHash, createResult, getInputExportPath, getRecursiveDirFiles, showErrorModule, stringToNumber, useUserHashKey } from './core/utils.js';
package/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  export { ActionsEventEnum } from './types/event/actions.js';
2
2
  export { core, logger } from './global.js';
3
3
  export { defineChildren } from './app/define-chidren.js';
4
+ export { defineResponse, lazy } from './app/define-response.js';
4
5
  export { onGroup } from './app/event-group.js';
5
6
  export { OnMiddleware, onMiddleware } from './app/event-middleware.js';
6
7
  export { OnProcessor, onProcessor } from './app/event-processor.js';
@@ -15,7 +16,7 @@ export { useObserver, useSubscribe } from './app/hook-use-subscribe.js';
15
16
  export { loadChildren, loadChildrenFile } from './app/load.js';
16
17
  export { createDataFormat, createEventValue, format, sendToChannel, sendToUser } from './app/message-api.js';
17
18
  export { Ark, BT, Image, ImageFile, ImageURL, Link, MD, Mention, Text } from './app/message-format.js';
18
- export { ChildrenApp, Core, Logger, Middleware, ProcessorEventAutoClearMap, ProcessorEventUserAudoClearMap, Response, State, StateSubscribe, SubscribeList } from './app/store.js';
19
+ export { ChildrenApp, Core, Logger, Middleware, ProcessorEventAutoClearMap, ProcessorEventUserAudoClearMap, Response, ResponseRouter, State, StateSubscribe, SubscribeList } from './app/store.js';
19
20
  export { ResultCode } from './core/variable.js';
20
21
  export { ConfigCore, getConfig, getConfigValue } from './core/config.js';
21
22
  export { createEventName, createHash, createResult, getInputExportPath, getRecursiveDirFiles, showErrorModule, stringToNumber, useUserHashKey } from './core/utils.js';
@@ -23,3 +24,14 @@ export { cbpClient } from './cbp/client.js';
23
24
  export { cbpServer } from './cbp/server.js';
24
25
  export { cbpPlatform } from './cbp/platform.js';
25
26
  export { run, start } from './main.js';
27
+
28
+ // 导出类型
29
+ ['SIGINT', 'SIGTERM', 'SIGQUIT', 'disconnect'].forEach(sig => {
30
+ process?.on?.(sig, () => {
31
+ logger?.info?.(`[alemonjs][${sig}] 收到信号,正在关闭...`);
32
+ setImmediate(() => process.exit(0));
33
+ });
34
+ });
35
+ process?.on?.('exit', code => {
36
+ logger?.info?.(`[alemonjs][exit] 进程退出,code=${code}`);
37
+ });
@@ -1,5 +1,9 @@
1
1
  import { StoreResponseItem, StoreMiddlewareItem } from '../store/res.js';
2
2
 
3
+ type StroreParam = {
4
+ response: StoreResponseItem[];
5
+ middleware: StoreMiddlewareItem[];
6
+ };
3
7
  /**
4
8
  * 子模块生命周期
5
9
  */
@@ -8,20 +12,17 @@ type ChildrenCycle = {
8
12
  * 创建时
9
13
  * @returns
10
14
  */
11
- onCreated?: () => void;
15
+ onCreated?: () => (void | Promise<void>);
12
16
  /**
13
17
  * 挂载时。得到属于自己的 store
14
18
  * @returns
15
19
  */
16
- onMounted?: (strore: {
17
- response: StoreResponseItem[];
18
- middleware: StoreMiddlewareItem[];
19
- }) => void;
20
+ onMounted?: (store: StroreParam) => (void | Promise<void>);
20
21
  /**
21
22
  * 卸载时
22
23
  * @returns
23
24
  */
24
- unMounted?: (error: any) => void;
25
+ unMounted?: (error: any) => (void | Promise<void>);
25
26
  };
26
27
  /**
27
28
  * 控制生命周期
@@ -50,10 +50,21 @@ type OnMiddlewareValue<C, T extends EventKeys> = {
50
50
  current: C;
51
51
  select: T | T[];
52
52
  };
53
- /**
54
- *
55
- */
56
- type DefineChildrenCallback = (() => Promise<ChildrenCycle> | ChildrenCycle) | ChildrenCycle;
53
+ type ResponseRoute = {
54
+ regular?: RegExp;
55
+ handler: () => Promise<any>;
56
+ children?: ResponseRoute[];
57
+ };
58
+ type DefineResponseFunc = (responses: ResponseRoute[]) => {
59
+ current: ResponseRoute[];
60
+ };
61
+ type childrenCallbackRes = {
62
+ response?: ReturnType<DefineResponseFunc>;
63
+ };
64
+ type childrenCallback = ChildrenCycle & {
65
+ register?: () => ((childrenCallbackRes | void)) | Promise<(childrenCallbackRes | void)>;
66
+ };
67
+ type DefineChildrenCallback = (() => Promise<childrenCallback> | childrenCallback) | childrenCallback;
57
68
  /**
58
69
  * 定义子模块
59
70
  */
@@ -61,10 +72,7 @@ type DefineChildrenValue = {
61
72
  _name: 'app';
62
73
  callback: DefineChildrenCallback;
63
74
  };
64
- /**
65
- *
66
- */
67
- type DefineChildrenFunc = (callback: (() => ChildrenCycle) | ChildrenCycle) => DefineChildrenValue;
75
+ type DefineChildrenFunc = (callback: (() => childrenCallback) | childrenCallback) => DefineChildrenValue;
68
76
  /**
69
77
  * 函数
70
78
  */
@@ -91,4 +99,4 @@ type OnDataFormatFunc = (...data: DataEnums[]) => DataEnums[];
91
99
  type OnGroupItem<C = any, T extends EventKeys = EventKeys> = OnResponseValue<C, T> | OnMiddlewareValue<C, T>;
92
100
  type OnGroupFunc = <C, T extends EventKeys, TFirst extends OnGroupItem<C, T>>(...calls: [TFirst, ...Array<TFirst>]) => TFirst;
93
101
 
94
- export type { Current, CurrentResult, CurrentResultValue, DefineChildrenCallback, DefineChildrenFunc, DefineChildrenValue, DefinePlatformCallback, DefinePlatformFunc, DefinePlatformValue, OnDataFormatFunc, OnGroupFunc, OnGroupItem, OnMiddlewareFunc, OnMiddlewareReversalFunc, OnMiddlewareReversalFuncBack, OnMiddlewareValue, OnResponseFunc, OnResponseReversalFunc, OnResponseReversalFuncBack, OnResponseValue, OnSelectsFunc };
102
+ export type { Current, CurrentResult, CurrentResultValue, DefineChildrenCallback, DefineChildrenFunc, DefineChildrenValue, DefinePlatformCallback, DefinePlatformFunc, DefinePlatformValue, DefineResponseFunc, OnDataFormatFunc, OnGroupFunc, OnGroupItem, OnMiddlewareFunc, OnMiddlewareReversalFunc, OnMiddlewareReversalFuncBack, OnMiddlewareValue, OnResponseFunc, OnResponseReversalFunc, OnResponseReversalFuncBack, OnResponseValue, OnSelectsFunc, ResponseRoute, childrenCallback, childrenCallbackRes };
@@ -0,0 +1 @@
1
+ expect;
@@ -1,3 +1,4 @@
1
+ import { childrenCallbackRes } from '../event/index.js';
1
2
  import { ChildrenCycle } from '../cycle/index.js';
2
3
  import { EventKeys } from '../event/map.js';
3
4
 
@@ -70,6 +71,7 @@ type StoreChildrenApp = {
70
71
  middleware: StoreMiddlewareItem[];
71
72
  response: StoreResponseItem[];
72
73
  cycle: ChildrenCycle;
74
+ register?: childrenCallbackRes;
73
75
  };
74
76
 
75
77
  export type { StoreChildrenApp, StoreMiddleware, StoreMiddlewareItem, StoreResponse, StoreResponseItem };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alemonjs",
3
- "version": "2.1.0-alpha.45",
3
+ "version": "2.1.0-alpha.47",
4
4
  "description": "bot script",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",