oox 0.3.0-beta9 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +29 -32
  3. package/app.js +131 -143
  4. package/bin/argv.js +63 -70
  5. package/bin/cli.js +57 -43
  6. package/bin/configurer.js +60 -62
  7. package/bin/loader.mjs +392 -279
  8. package/bin/proxy-import.js +12 -0
  9. package/bin/proxy-require.js +88 -0
  10. package/bin/register.js +46 -55
  11. package/bin/starter.js +63 -66
  12. package/index.js +155 -168
  13. package/index.mjs +4 -4
  14. package/logger.js +25 -40
  15. package/modules/http/index.js +286 -192
  16. package/modules/http/router.js +205 -0
  17. package/modules/http/utils.js +75 -73
  18. package/modules/index.js +86 -88
  19. package/modules/module.js +11 -16
  20. package/modules/socketio/client.js +97 -101
  21. package/modules/socketio/index.js +171 -168
  22. package/modules/socketio/server.js +188 -136
  23. package/modules/socketio/socket.js +1 -4
  24. package/package.json +14 -12
  25. package/types/app.d.ts +50 -51
  26. package/types/bin/argv.d.ts +8 -8
  27. package/types/bin/cli.d.ts +6 -2
  28. package/types/bin/configurer.d.ts +3 -1
  29. package/types/bin/proxy-import.d.ts +4 -0
  30. package/types/bin/proxy-require.d.ts +5 -0
  31. package/types/bin/register.d.ts +1 -1
  32. package/types/bin/starter.d.ts +5 -1
  33. package/types/index.d.ts +78 -76
  34. package/types/logger.d.ts +5 -4
  35. package/types/modules/http/index.d.ts +65 -47
  36. package/types/modules/http/router.d.ts +49 -0
  37. package/types/modules/http/utils.d.ts +14 -17
  38. package/types/modules/index.d.ts +24 -24
  39. package/types/modules/module.d.ts +11 -13
  40. package/types/modules/socketio/client.d.ts +23 -23
  41. package/types/modules/socketio/index.d.ts +37 -37
  42. package/types/modules/socketio/server.d.ts +44 -35
  43. package/types/modules/socketio/socket.d.ts +11 -11
  44. package/types/utils.d.ts +6 -6
  45. package/utils.js +57 -63
  46. package/bin/proxyer.js +0 -61
  47. package/types/bin/proxyer.d.ts +0 -1
@@ -0,0 +1,205 @@
1
+ export default class Router {
2
+ routes = new Map();
3
+ globalMiddleware = [];
4
+ // 注册GET路由
5
+ get(path, ...args) {
6
+ const { handler, middleware } = this.parseRouteArgs(args);
7
+ this.addRoute('GET', path, handler, middleware);
8
+ }
9
+ // 注册POST路由
10
+ post(path, ...args) {
11
+ const { handler, middleware } = this.parseRouteArgs(args);
12
+ this.addRoute('POST', path, handler, middleware);
13
+ }
14
+ // 注册PUT路由
15
+ put(path, ...args) {
16
+ const { handler, middleware } = this.parseRouteArgs(args);
17
+ this.addRoute('PUT', path, handler, middleware);
18
+ }
19
+ // 注册DELETE路由
20
+ delete(path, ...args) {
21
+ const { handler, middleware } = this.parseRouteArgs(args);
22
+ this.addRoute('DELETE', path, handler, middleware);
23
+ }
24
+ // 解析路由参数,支持多种传入方式
25
+ parseRouteArgs(args) {
26
+ let handler;
27
+ let middleware = [];
28
+ if (args.length === 0) {
29
+ throw new Error('No handler provided for route');
30
+ }
31
+ // 方式1: [handler] 或 [middlewareArray, handler]
32
+ if (args.length === 1) {
33
+ if (typeof args[0] === 'function') {
34
+ handler = args[0];
35
+ }
36
+ else {
37
+ throw new Error('Invalid route handler');
38
+ }
39
+ }
40
+ // 方式2: [handler, middlewareArray] 或 [middleware1, middleware2, handler] 或 [middlewareArray, handler]
41
+ else {
42
+ // 检查最后一个参数是否是函数(处理器)
43
+ if (typeof args[args.length - 1] === 'function') {
44
+ handler = args[args.length - 1];
45
+ // 前面的所有都是中间件
46
+ const middleArgs = args.slice(0, -1);
47
+ // 展平中间件数组
48
+ for (const arg of middleArgs) {
49
+ if (Array.isArray(arg)) {
50
+ middleware.push(...arg);
51
+ }
52
+ else if (typeof arg === 'function') {
53
+ middleware.push(arg);
54
+ }
55
+ }
56
+ }
57
+ // 检查第一个参数是否是函数
58
+ else if (typeof args[0] === 'function') {
59
+ handler = args[0];
60
+ // 后面的是中间件
61
+ const middleArgs = args.slice(1);
62
+ for (const arg of middleArgs) {
63
+ if (Array.isArray(arg)) {
64
+ middleware.push(...arg);
65
+ }
66
+ else if (typeof arg === 'function') {
67
+ middleware.push(arg);
68
+ }
69
+ }
70
+ }
71
+ else {
72
+ throw new Error('Invalid route arguments');
73
+ }
74
+ }
75
+ return { handler, middleware };
76
+ }
77
+ // 注册全局中间件
78
+ use(middleware) {
79
+ this.globalMiddleware.push(middleware);
80
+ }
81
+ // 注册特定路径的中间件
82
+ usePath(path, middleware) {
83
+ // 实现路径级中间件
84
+ }
85
+ // 添加路由
86
+ addRoute(method, path, handler, middleware = []) {
87
+ if (!this.routes.has(method)) {
88
+ this.routes.set(method, []);
89
+ }
90
+ // 编译路径为正则表达式,支持路径参数
91
+ const { regex, paramNames } = this.compilePath(path);
92
+ this.routes.get(method).push({
93
+ path,
94
+ method,
95
+ handler,
96
+ middleware,
97
+ regex,
98
+ paramNames
99
+ });
100
+ }
101
+ // 编译路径为正则表达式
102
+ compilePath(path) {
103
+ const paramNames = [];
104
+ const regexPattern = path
105
+ .replace(/:([^/]+)/g, (_, paramName) => {
106
+ paramNames.push(paramName);
107
+ return '([^/]+)';
108
+ })
109
+ .replace(/\//g, '\\/')
110
+ .replace(/\*/g, '.*');
111
+ return {
112
+ regex: new RegExp(`^${regexPattern}$`),
113
+ paramNames
114
+ };
115
+ }
116
+ // 匹配路由
117
+ match(method, path) {
118
+ const routes = this.routes.get(method) || [];
119
+ for (const route of routes) {
120
+ const match = path.match(route.regex);
121
+ if (match) {
122
+ const params = {};
123
+ route.paramNames.forEach((paramName, index) => {
124
+ params[paramName] = match[index + 1];
125
+ });
126
+ return { route, params };
127
+ }
128
+ }
129
+ return null;
130
+ }
131
+ // 创建请求对象
132
+ createRequestObject(originalRequest, url) {
133
+ return {
134
+ originalRequest,
135
+ url,
136
+ method: originalRequest.method || 'GET',
137
+ path: url.pathname,
138
+ query: Object.fromEntries(url.searchParams),
139
+ params: {},
140
+ headers: originalRequest.headers,
141
+ body: null
142
+ };
143
+ }
144
+ // 创建响应对象
145
+ createResponseObject(originalResponse) {
146
+ let statusCode = 200;
147
+ return {
148
+ originalResponse,
149
+ status(code) {
150
+ statusCode = code;
151
+ return this;
152
+ },
153
+ json(data) {
154
+ const jsonString = JSON.stringify(data);
155
+ this.originalResponse.statusCode = statusCode;
156
+ this.originalResponse.setHeader('Content-Type', 'application/json');
157
+ this.originalResponse.setHeader('Content-Length', Buffer.byteLength(jsonString));
158
+ this.originalResponse.end(jsonString);
159
+ },
160
+ send(data) {
161
+ const dataString = typeof data === 'string' ? data : JSON.stringify(data);
162
+ this.originalResponse.statusCode = statusCode;
163
+ this.originalResponse.setHeader('Content-Type', 'text/plain');
164
+ this.originalResponse.setHeader('Content-Length', Buffer.byteLength(dataString));
165
+ this.originalResponse.end(dataString);
166
+ },
167
+ end(data) {
168
+ this.originalResponse.statusCode = statusCode;
169
+ this.originalResponse.end(data);
170
+ }
171
+ };
172
+ }
173
+ // 执行中间件
174
+ async executeMiddleware(middleware, req, res) {
175
+ for (const fn of middleware) {
176
+ let nextCalled = false;
177
+ const next = () => { nextCalled = true; };
178
+ const result = fn(req, res, next);
179
+ if (result instanceof Promise) {
180
+ await result;
181
+ }
182
+ if (!nextCalled) {
183
+ return false; // 中间件已结束响应
184
+ }
185
+ }
186
+ return true; // 所有中间件都已执行
187
+ }
188
+ // 处理路由请求
189
+ async handleRoute(route, params, req, res) {
190
+ req.params = params;
191
+ // 执行全局中间件
192
+ const globalMiddlewareContinue = await this.executeMiddleware(this.globalMiddleware, req, res);
193
+ if (!globalMiddlewareContinue)
194
+ return;
195
+ // 执行路由中间件
196
+ const routeMiddlewareContinue = await this.executeMiddleware(route.middleware, req, res);
197
+ if (!routeMiddlewareContinue)
198
+ return;
199
+ // 执行路由处理函数
200
+ const result = route.handler(req, res);
201
+ if (result instanceof Promise) {
202
+ await result;
203
+ }
204
+ }
205
+ }
@@ -1,73 +1,75 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.httpRequest = exports.parseHTTPBody = exports.stream2buffer = void 0;
4
- const http = require("node:http");
5
- /**
6
- * Stream => Buffer
7
- */
8
- function stream2buffer(stream, totalLength = 0) {
9
- return new Promise(function (resolve, reject) {
10
- let buffers = [];
11
- stream.on('error', reject);
12
- if (totalLength) {
13
- stream.on('data', function (data) { buffers.push(data); });
14
- }
15
- else {
16
- stream.on('data', function (data) {
17
- buffers.push(data);
18
- totalLength += data.length;
19
- });
20
- }
21
- stream.on('end', function () { resolve(Buffer.concat(buffers, totalLength)); });
22
- });
23
- }
24
- exports.stream2buffer = stream2buffer;
25
- /**
26
- * Request => JSONObject
27
- */
28
- async function parseHTTPBody(request) {
29
- if (request.method === 'GET')
30
- return null;
31
- let contentType = request.headers['content-type'];
32
- // application/json; charset=utf-8
33
- if (contentType)
34
- contentType = contentType.split(';')[0].trim();
35
- const contentSize = request.headers['content-length'];
36
- const buffer = await stream2buffer(request, +contentSize || 0);
37
- if (contentSize && buffer.length !== +contentSize)
38
- throw new Error('Content-Length Incorrect');
39
- const bodyString = buffer.toString();
40
- if ('application/json' === contentType) {
41
- return JSON.parse(bodyString);
42
- }
43
- else {
44
- return bodyString;
45
- }
46
- }
47
- exports.parseHTTPBody = parseHTTPBody;
48
- /**
49
- * http request
50
- */
51
- function httpRequest(url, options, body) {
52
- return new Promise(function (resolve, reject) {
53
- const request = http.request(url, options, async function (response) {
54
- try {
55
- const result = await parseHTTPBody(response);
56
- resolve(result);
57
- }
58
- catch (error) {
59
- const decoration = new Error(`${response.statusCode} - ${error.message}`);
60
- reject(decoration);
61
- }
62
- });
63
- request.on('error', reject);
64
- if (body) {
65
- request.method = 'POST';
66
- request.setHeader('Content-Type', 'application/json');
67
- request.setHeader('Content-Length', Buffer.byteLength(body));
68
- request.write(body);
69
- }
70
- request.end();
71
- });
72
- }
73
- exports.httpRequest = httpRequest;
1
+ import * as http from 'node:http';
2
+ import * as https from 'node:https';
3
+ /**
4
+ * Stream => Buffer
5
+ */
6
+ export function stream2buffer(stream, totalLength = 0) {
7
+ return new Promise(function (resolve, reject) {
8
+ let buffers = [];
9
+ stream.on('error', reject);
10
+ if (totalLength) {
11
+ stream.on('data', function (data) { buffers.push(data); });
12
+ }
13
+ else {
14
+ stream.on('data', function (data) {
15
+ buffers.push(data);
16
+ totalLength += data.length;
17
+ });
18
+ }
19
+ stream.on('end', function () { resolve(Buffer.concat(buffers, totalLength)); });
20
+ });
21
+ }
22
+ /**
23
+ * Request => JSONObject
24
+ */
25
+ export async function parseHTTPBody(request) {
26
+ if (request.method === 'GET')
27
+ return null;
28
+ let contentType = request.headers['content-type'];
29
+ // application/json; charset=utf-8
30
+ if (contentType)
31
+ contentType = contentType.split(';')[0].trim();
32
+ const contentLength = request.headers['content-length'];
33
+ if (!contentLength || contentLength === '0')
34
+ return null;
35
+ const contentSize = +contentLength;
36
+ const buffer = await stream2buffer(request, contentSize);
37
+ if (buffer.length !== contentSize)
38
+ throw new Error('Content-Length Incorrect');
39
+ switch (contentType) {
40
+ case 'application/json':
41
+ return JSON.parse(buffer.toString());
42
+ case 'text/plain':
43
+ return buffer.toString();
44
+ default:
45
+ return buffer;
46
+ }
47
+ }
48
+ /**
49
+ * http request
50
+ */
51
+ export function httpRequest(url, options, body) {
52
+ return new Promise(function (resolve, reject) {
53
+ const urlObj = typeof url === 'string' ? new URL(url) : url;
54
+ const protocol = urlObj.protocol;
55
+ const client = protocol === 'https:' ? https : http;
56
+ const request = client.request(url, options, async function (response) {
57
+ try {
58
+ const result = await parseHTTPBody(response);
59
+ resolve(result);
60
+ }
61
+ catch (error) {
62
+ const decoration = new Error(`${response.statusCode} - ${error.message}`);
63
+ reject(decoration);
64
+ }
65
+ });
66
+ request.on('error', reject);
67
+ if (body) {
68
+ request.method = 'POST';
69
+ request.setHeader('Content-Type', 'application/json');
70
+ request.setHeader('Content-Length', Buffer.byteLength(body));
71
+ request.write(body);
72
+ }
73
+ request.end();
74
+ });
75
+ }
package/modules/index.js CHANGED
@@ -1,88 +1,86 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const module_1 = require("./module");
4
- const http_1 = require("./http");
5
- const socketio_1 = require("./socketio");
6
- class Modules extends module_1.default {
7
- /**
8
- * the module unique name
9
- */
10
- name = 'oox:modules';
11
- /**
12
- * FIFO queue for modules starting
13
- */
14
- #queue = [];
15
- /**
16
- * all modules map
17
- */
18
- #map = new Map();
19
- /**
20
- * all builtin modules
21
- */
22
- builtins = {
23
- http: new http_1.default,
24
- socketio: new socketio_1.default,
25
- };
26
- constructor() {
27
- super();
28
- this.add(this.builtins.http);
29
- this.add(this.builtins.socketio);
30
- }
31
- add(module) {
32
- if (!module.name || 'string' !== typeof module.name)
33
- throw new Error(`Module<${module.name}> has noname`);
34
- if (this.#map.has(module.name))
35
- throw new Error(`Module<${module.name}> has exists`);
36
- this.#map.set(module.name, module);
37
- this.#queue.push(module);
38
- return this;
39
- }
40
- get(name) {
41
- return this.#map.get(name);
42
- }
43
- async remove(name) {
44
- const module = this.get(name);
45
- if (!module)
46
- return;
47
- await module.stop();
48
- const index = this.#queue.indexOf(module);
49
- this.#queue.splice(index, 1);
50
- this.#map.delete(name);
51
- }
52
- setConfig(config) {
53
- for (const module of this.#queue) {
54
- if (module.name in config) {
55
- const moduleConfig = config[module.name];
56
- if (moduleConfig) {
57
- module.setConfig(moduleConfig);
58
- }
59
- else {
60
- module.setConfig({ disabled: true });
61
- }
62
- }
63
- else {
64
- module.setConfig({});
65
- }
66
- config[module.name] = module.getConfig();
67
- }
68
- }
69
- async serve() {
70
- try {
71
- for (const module of this.#queue) {
72
- if (!module.getConfig().disabled) {
73
- await module.serve();
74
- }
75
- }
76
- }
77
- catch (error) {
78
- await this.stop();
79
- throw error;
80
- }
81
- }
82
- async stop() {
83
- for (const module of this.#queue) {
84
- await module.stop();
85
- }
86
- }
87
- }
88
- exports.default = Modules;
1
+ import Module from './module.js';
2
+ import HTTP from './http/index.js';
3
+ import SocketIO from './socketio/index.js';
4
+ export default class Modules extends Module {
5
+ /**
6
+ * the module unique name
7
+ */
8
+ name = 'oox:modules';
9
+ /**
10
+ * FIFO queue for modules starting
11
+ */
12
+ #queue = [];
13
+ /**
14
+ * all modules map
15
+ */
16
+ #map = new Map();
17
+ /**
18
+ * all builtin modules
19
+ */
20
+ builtins = {
21
+ http: new HTTP,
22
+ socketio: new SocketIO,
23
+ };
24
+ constructor() {
25
+ super();
26
+ this.add(this.builtins.http);
27
+ this.add(this.builtins.socketio);
28
+ }
29
+ add(module) {
30
+ if (!module.name || 'string' !== typeof module.name)
31
+ throw new Error(`Module<${module.name}> has noname`);
32
+ if (this.#map.has(module.name))
33
+ throw new Error(`Module<${module.name}> has exists`);
34
+ this.#map.set(module.name, module);
35
+ this.#queue.push(module);
36
+ return this;
37
+ }
38
+ get(name) {
39
+ return this.#map.get(name);
40
+ }
41
+ async remove(name) {
42
+ const module = this.get(name);
43
+ if (!module)
44
+ return;
45
+ await module.stop();
46
+ const index = this.#queue.indexOf(module);
47
+ this.#queue.splice(index, 1);
48
+ this.#map.delete(name);
49
+ }
50
+ setConfig(config) {
51
+ for (const module of this.#queue) {
52
+ if (module.name in config) {
53
+ const moduleConfig = config[module.name];
54
+ if ('boolean' === typeof moduleConfig) {
55
+ // eg: http=yes/no
56
+ module.setConfig({ enabled: moduleConfig });
57
+ }
58
+ else {
59
+ module.setConfig(moduleConfig);
60
+ }
61
+ }
62
+ else {
63
+ module.setConfig({ enabled: true });
64
+ }
65
+ config[module.name] = module.getConfig();
66
+ }
67
+ }
68
+ async serve() {
69
+ try {
70
+ for (const module of this.#queue) {
71
+ if (module.getConfig().enabled) {
72
+ await module.serve();
73
+ }
74
+ }
75
+ }
76
+ catch (error) {
77
+ await this.stop();
78
+ throw error;
79
+ }
80
+ }
81
+ async stop() {
82
+ for (const module of this.#queue) {
83
+ await module.stop();
84
+ }
85
+ }
86
+ }
package/modules/module.js CHANGED
@@ -1,16 +1,11 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ModuleConfig = void 0;
4
- class ModuleConfig {
5
- disabled = false;
6
- }
7
- exports.ModuleConfig = ModuleConfig;
8
- class Module {
9
- config;
10
- name;
11
- setConfig(config) { }
12
- getConfig() { return this.config; }
13
- async serve() { }
14
- async stop() { }
15
- }
16
- exports.default = Module;
1
+ export class ModuleConfig {
2
+ enabled = true;
3
+ }
4
+ export default class Module {
5
+ config;
6
+ name;
7
+ setConfig(config) { }
8
+ getConfig() { return this.config; }
9
+ async serve() { }
10
+ async stop() { }
11
+ }