@yumerijs/core 1.3.3 → 2.0.1

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/server.js CHANGED
@@ -43,8 +43,6 @@ const http_1 = __importDefault(require("http"));
43
43
  const fs = __importStar(require("fs"));
44
44
  const path = __importStar(require("path"));
45
45
  const url_1 = require("url");
46
- const ws_1 = __importDefault(require("ws"));
47
- const formidable = __importStar(require("formidable"));
48
46
  const mime = __importStar(require("mime-types"));
49
47
  const logger = new logger_1.Logger('server');
50
48
  class Server {
@@ -53,19 +51,16 @@ class Server {
53
51
  host;
54
52
  enableCors;
55
53
  staticDir;
56
- enableWs;
57
54
  httpServer = null;
58
- wsServer = null;
59
55
  constructor(core, config = {}) {
60
56
  this.core = core;
61
57
  this.port = config.port ?? 14510;
62
58
  this.host = config.host ?? '0.0.0.0';
63
59
  this.enableCors = config.enableCors ?? true;
64
60
  this.staticDir = config.staticDir ?? 'static';
65
- this.enableWs = config.enableWs ?? true;
66
61
  }
67
- createSession(ip, cookies, res, req, extra = {}) {
68
- const session = new session_1.Session(ip, cookies, this, req, res);
62
+ createSession(ip, cookies, res, req, pathname, extra = {}) {
63
+ const session = new session_1.Session(ip, cookies, this, req, res, pathname);
69
64
  Object.assign(session.properties, extra);
70
65
  session.protocol = extra.protocol ?? 'http';
71
66
  return session;
@@ -85,46 +80,6 @@ class Server {
85
80
  const xff = req.headers['x-forwarded-for'];
86
81
  return xff ? xff.split(',')[0].trim() : req.socket.remoteAddress || '127.0.0.1';
87
82
  }
88
- async parseRequestBody(req) {
89
- return new Promise((resolve, reject) => {
90
- const contentType = (req.headers['content-type'] || '').toLowerCase();
91
- if (contentType.includes('application/json') || contentType.includes('application/x-www-form-urlencoded')) {
92
- let body = '';
93
- req.on('data', chunk => body += chunk.toString());
94
- req.on('end', () => {
95
- try {
96
- if (contentType.includes('application/json'))
97
- resolve(JSON.parse(body));
98
- else {
99
- const params = new URLSearchParams(body);
100
- const parsed = {};
101
- params.forEach((v, k) => parsed[k] = v);
102
- resolve(parsed);
103
- }
104
- }
105
- catch (e) {
106
- reject(e);
107
- }
108
- });
109
- }
110
- else if (contentType.includes('multipart/form-data')) {
111
- const form = formidable.formidable({});
112
- form.parse(req, (err, fields) => {
113
- if (err)
114
- return reject(err);
115
- const parsed = {};
116
- Object.keys(fields).forEach(k => {
117
- const val = fields[k];
118
- parsed[k] = Array.isArray(val) && val.length === 1 ? val[0] : val;
119
- });
120
- resolve(parsed);
121
- });
122
- }
123
- else
124
- resolve({});
125
- req.on('error', reject);
126
- });
127
- }
128
83
  serveStaticFile(pathname, res) {
129
84
  const fullPath = path.join(process.cwd(), this.staticDir, pathname);
130
85
  fs.readFile(fullPath, (err, data) => {
@@ -154,25 +109,9 @@ class Server {
154
109
  const queryParams = url.searchParams;
155
110
  const ip = this.getClientIP(req);
156
111
  const cookies = this.parseCookies(req);
157
- const session = this.createSession(ip, cookies, res, req, { protocol: 'http', header: req.headers });
158
- if (req.method?.toLowerCase() === 'post') {
159
- try {
160
- const body = await this.parseRequestBody(req);
161
- Object.entries(body).forEach(([k, v]) => {
162
- if (typeof v === 'string')
163
- queryParams.set(k, v);
164
- else if (Array.isArray(v))
165
- v.forEach(val => queryParams.append(k, val));
166
- });
167
- }
168
- catch (err) {
169
- res.writeHead(400, { 'Content-Type': 'text/plain' });
170
- res.end('Invalid request body');
171
- logger.error('Request body parse error:', err);
172
- return;
173
- }
174
- }
112
+ const session = this.createSession(ip, cookies, res, req, pathname, { protocol: 'http', header: req.headers });
175
113
  const route = this.core.getRoute(pathname);
114
+ const rootroute = this.core.getRoute('root');
176
115
  if (route && route.allowedMethods.includes(req.method ?? 'GET')) {
177
116
  const matched = await this.core.executeRoute(pathname, session, queryParams);
178
117
  if (!matched) {
@@ -188,42 +127,59 @@ class Server {
188
127
  res.end(session.body);
189
128
  }
190
129
  }
130
+ else if (rootroute && rootroute.allowedMethods.includes(req.method ?? 'GET')) {
131
+ const matched = await this.core.executeRoute('root', session, queryParams);
132
+ if (!matched) {
133
+ this.serveStaticFile(pathname, res);
134
+ }
135
+ else {
136
+ let head = session.head;
137
+ head['Set-Cookie'] = Object.entries(session.newCookie).map(([k, v]) => `${k}=${v}`);
138
+ if (this.enableCors) {
139
+ head['Access-Control-Allow-Origin'] = '*';
140
+ }
141
+ res.writeHead(session.status ?? 200, head);
142
+ res.end(session.body);
143
+ }
144
+ }
191
145
  else {
192
146
  this.serveStaticFile(pathname, res);
193
147
  }
194
148
  });
195
- if (this.enableWs) {
196
- this.wsServer = new ws_1.default.Server({ server: this.httpServer });
197
- this.wsServer.on('connection', (ws, req) => {
198
- const url = new url_1.URL(req.url || '/', `http://${req.headers.host}`);
199
- const pathname = url.pathname;
200
- const queryParams = url.searchParams;
201
- const ip = this.getClientIP(req);
202
- const cookies = this.parseCookies(req);
203
- const session = this.createSession(ip, cookies, undefined, req, { ws, protocol: 'ws' });
204
- ws.on('message', async (msg) => {
205
- try {
206
- const data = JSON.parse(msg.toString());
207
- Object.entries(data).forEach(([k, v]) => queryParams.set(k, v));
208
- }
209
- catch {
210
- queryParams.set('message', msg.toString());
211
- }
212
- await this.core.executeRoute(pathname, session, queryParams);
213
- });
214
- this.core.executeRoute(pathname, session, queryParams).catch(err => {
215
- logger.error(`WS initial route error for ${pathname}:`, err);
216
- ws.close(1011, 'Internal error');
217
- });
218
- });
219
- }
149
+ this.httpServer.on('upgrade', async (req, socket, head) => {
150
+ const url = new url_1.URL(req.url || '/', `http://${req.headers.host}`);
151
+ const pathname = url.pathname;
152
+ const queryParams = url.searchParams;
153
+ const ip = this.getClientIP(req);
154
+ const cookies = this.parseCookies(req);
155
+ const session = this.createSession(ip, cookies, null, req, pathname, { protocol: 'http', header: req.headers });
156
+ const route = this.core.getRoute(pathname);
157
+ if (route && route.ws != null) {
158
+ const matched = await this.core.executeRoute(pathname, session, queryParams);
159
+ if (!matched) {
160
+ socket.write('HTTP/1.1 400 Bad Request\r\n' +
161
+ 'Content-Type: text/plain\r\n' +
162
+ 'Connection: close\r\n');
163
+ socket.destroy();
164
+ }
165
+ else {
166
+ route.ws.handleUpgrade(req, socket, head, (ws) => {
167
+ route.ws.emit('connection', ws, req, session);
168
+ });
169
+ }
170
+ }
171
+ else {
172
+ socket.write('HTTP/1.1 400 Bad Request\r\n' +
173
+ 'Content-Type: text/plain\r\n' +
174
+ 'Connection: close\r\n');
175
+ socket.destroy();
176
+ }
177
+ });
220
178
  this.httpServer.listen(this.port, this.host, () => {
221
179
  logger.info(`Server listening on ${this.host}:${this.port}`);
222
180
  });
223
181
  }
224
182
  stop() {
225
- if (this.wsServer)
226
- this.wsServer.close();
227
183
  if (this.httpServer)
228
184
  this.httpServer.close(() => logger.info('Server stopped'));
229
185
  }
package/dist/session.d.ts CHANGED
@@ -5,6 +5,12 @@
5
5
  **/
6
6
  import { Server } from './server';
7
7
  import { IncomingMessage, ServerResponse } from 'http';
8
+ type ParsedParams = Record<string, string | string[] | undefined>;
9
+ export interface Client {
10
+ req: IncomingMessage;
11
+ res: ServerResponse;
12
+ headers?: Record<string, string>;
13
+ }
8
14
  export declare class Session {
9
15
  ip: string;
10
16
  cookie: Record<string, string>;
@@ -16,12 +22,42 @@ export declare class Session {
16
22
  status: number;
17
23
  body: any;
18
24
  properties?: Record<string, any>;
19
- res: any;
20
- req: any;
25
+ client: Client;
21
26
  server: Server;
22
27
  protocol: string;
23
- constructor(ip: string, cookie: Record<string, string>, server: Server, req?: IncomingMessage, res?: ServerResponse, query?: Record<string, string>);
28
+ pathname: string;
29
+ languages: string[];
30
+ /**
31
+ * @constructor
32
+ * @param ip 用户IP
33
+ * @param cookie 会话cookie
34
+ * @param query 请求字符串
35
+ */
36
+ constructor(ip: string, cookie: Record<string, string>, server: Server, req?: IncomingMessage, res?: ServerResponse, pathname?: string, query?: Record<string, string>);
37
+ /**
38
+ * 解析 Accept-Language 字符串为排序后的语言数组
39
+ * @param header Accept-Language 头,比如 "zh-CN,zh-TW;q=0.8,en-US;q=0.6"
40
+ * @returns 按优先级排序的语言数组,自动补上父语言
41
+ */
42
+ parseAcceptLanguages(header: string): any[];
43
+ /**
44
+ * 生成 sessionid
45
+ * @param ip 用户IP
46
+ * @param option 选项
47
+ */
24
48
  private generateId;
49
+ /**
50
+ * 解析请求体
51
+ * @param client 客户端
52
+ * @returns Promise<ParsedParams>
53
+ */
54
+ parseRequestBody(client?: Client): Promise<ParsedParams>;
55
+ /**
56
+ * 获取请求体
57
+ * @param req 请求对象
58
+ * @returns Promise<string>
59
+ */
60
+ getReqBody(req: IncomingMessage): Promise<string>;
25
61
  private md5;
26
62
  setData(key: string, value: any): void;
27
63
  deleteData(key: string): void;
@@ -30,4 +66,10 @@ export declare class Session {
30
66
  setMime(mimeType: 'png' | 'jpg' | 'jpeg' | 'pdf' | 'plain' | 'html' | 'json' | 'xml' | string): void;
31
67
  send(data: any): any;
32
68
  endsession(message: any): any;
69
+ /**
70
+ * 获取I18n文本
71
+ * @param name 文本点名称
72
+ */
73
+ text(name: string): any;
33
74
  }
75
+ export {};
package/dist/session.js CHANGED
@@ -4,12 +4,46 @@
4
4
  * @author: FireGuo
5
5
  * WindyPear-Team All right reserved
6
6
  **/
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
7
40
  var __importDefault = (this && this.__importDefault) || function (mod) {
8
41
  return (mod && mod.__esModule) ? mod : { "default": mod };
9
42
  };
10
43
  Object.defineProperty(exports, "__esModule", { value: true });
11
44
  exports.Session = void 0;
12
45
  const crypto_1 = __importDefault(require("crypto"));
46
+ const formidable = __importStar(require("formidable"));
13
47
  class Session {
14
48
  ip;
15
49
  cookie;
@@ -21,22 +55,27 @@ class Session {
21
55
  status = 200;
22
56
  body;
23
57
  properties = {};
24
- res = null;
25
- req = null;
58
+ client = null;
26
59
  server;
27
60
  protocol = 'http';
28
- /*
29
- * @ip: string,用户IP
30
- * @cookie: string,会话cookie
31
- * @query: string,请求字符串
61
+ pathname;
62
+ languages;
63
+ /**
64
+ * @constructor
65
+ * @param ip 用户IP
66
+ * @param cookie 会话cookie
67
+ * @param query 请求字符串
32
68
  */
33
- constructor(ip, cookie, server, req, res, query) {
69
+ constructor(ip, cookie, server, req, res, pathname, query) {
34
70
  this.ip = ip;
35
71
  this.cookie = cookie;
36
72
  this.query = query;
37
73
  this.server = server;
38
- this.req = req;
39
- this.res = res;
74
+ this.pathname = pathname;
75
+ this.client = {
76
+ req: req,
77
+ res: res
78
+ };
40
79
  this.head['Content-Type'] = 'text/plain';
41
80
  if (cookie.sessionid) {
42
81
  this.sessionid = cookie.sessionid;
@@ -45,16 +84,122 @@ class Session {
45
84
  this.sessionid = this.generateId(this.ip);
46
85
  this.newCookie.sessionid = this.sessionid;
47
86
  }
87
+ if (cookie.lang) {
88
+ this.languages = cookie.lang.split(',');
89
+ }
90
+ else if (req.headers['accept-language']) {
91
+ this.languages = this.parseAcceptLanguages(req.headers['accept-language']);
92
+ this.newCookie.lang = this.languages.join(',');
93
+ }
94
+ }
95
+ /**
96
+ * 解析 Accept-Language 字符串为排序后的语言数组
97
+ * @param header Accept-Language 头,比如 "zh-CN,zh-TW;q=0.8,en-US;q=0.6"
98
+ * @returns 按优先级排序的语言数组,自动补上父语言
99
+ */
100
+ parseAcceptLanguages(header) {
101
+ if (!header)
102
+ return [];
103
+ const langs = header
104
+ .split(',')
105
+ .map(item => {
106
+ const [lang, qStr] = item.trim().split(';');
107
+ const q = qStr ? parseFloat(qStr.split('=')[1]) || 1 : 1;
108
+ return { lang: lang.toLowerCase(), q };
109
+ })
110
+ .sort((a, b) => b.q - a.q);
111
+ const result = [];
112
+ const seen = new Set();
113
+ for (const { lang } of langs) {
114
+ if (!seen.has(lang)) {
115
+ result.push(lang);
116
+ seen.add(lang);
117
+ }
118
+ const parts = lang.split('-');
119
+ if (parts.length > 1) {
120
+ const base = parts[0];
121
+ if (!seen.has(base)) {
122
+ let insertIndex = -1;
123
+ for (let i = result.length - 1; i >= 0; i--) {
124
+ if (result[i].startsWith(base + '-')) {
125
+ insertIndex = i + 1;
126
+ break;
127
+ }
128
+ }
129
+ if (insertIndex === -1)
130
+ insertIndex = result.length;
131
+ result.splice(insertIndex, 0, base);
132
+ seen.add(base);
133
+ }
134
+ }
135
+ }
136
+ return result;
48
137
  }
49
- // 生成 sessionid
50
- /*
51
- * @ip: string,用户IP
52
- * @option: string,选项
138
+ /**
139
+ * 生成 sessionid
140
+ * @param ip 用户IP
141
+ * @param option 选项
53
142
  */
54
143
  generateId(ip, option) {
55
144
  const sessionId = this.md5(ip + Date.now().toString() + Math.random().toString()); // 添加随机性
56
145
  return sessionId;
57
146
  }
147
+ /**
148
+ * 解析请求体
149
+ * @param client 客户端
150
+ * @returns Promise<ParsedParams>
151
+ */
152
+ async parseRequestBody(client = this.client) {
153
+ const req = client.req;
154
+ return new Promise((resolve, reject) => {
155
+ const contentType = (req.headers['content-type'] || '').toLowerCase();
156
+ if (contentType.includes('application/json') || contentType.includes('application/x-www-form-urlencoded')) {
157
+ let body = '';
158
+ req.on('data', chunk => body += chunk.toString());
159
+ req.on('end', () => {
160
+ try {
161
+ if (contentType.includes('application/json'))
162
+ resolve(JSON.parse(body));
163
+ else {
164
+ const params = new URLSearchParams(body);
165
+ const parsed = {};
166
+ params.forEach((v, k) => parsed[k] = v);
167
+ resolve(parsed);
168
+ }
169
+ }
170
+ catch (e) {
171
+ reject(e);
172
+ }
173
+ });
174
+ }
175
+ else if (contentType.includes('multipart/form-data')) {
176
+ const form = formidable.formidable({});
177
+ form.parse(req, (err, fields) => {
178
+ if (err)
179
+ return reject(err);
180
+ const parsed = {};
181
+ Object.keys(fields).forEach(k => {
182
+ const val = fields[k];
183
+ parsed[k] = Array.isArray(val) && val.length === 1 ? val[0] : val;
184
+ });
185
+ resolve(parsed);
186
+ });
187
+ }
188
+ else
189
+ resolve({});
190
+ req.on('error', reject);
191
+ });
192
+ }
193
+ /**
194
+ * 获取请求体
195
+ * @param req 请求对象
196
+ * @returns Promise<string>
197
+ */
198
+ async getReqBody(req) {
199
+ let body = "";
200
+ req.on('data', chunk => body += chunk.toString());
201
+ return body;
202
+ }
58
203
  // MD5 加密
59
204
  md5(str) {
60
205
  const hash = crypto_1.default.createHash('md5');
@@ -107,10 +252,17 @@ class Session {
107
252
  }
108
253
  }
109
254
  send(data) {
110
- return this.res.send(data);
255
+ return this.client.res.write(data);
111
256
  }
112
257
  endsession(message) {
113
- return this.res.end(message);
258
+ return this.client.res.end(message);
259
+ }
260
+ /**
261
+ * 获取I18n文本
262
+ * @param name 文本点名称
263
+ */
264
+ text(name) {
265
+ return this.server.core.i18n.get(name, this.languages);
114
266
  }
115
267
  }
116
268
  exports.Session = Session;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yumerijs/core",
3
- "version": "1.3.3",
3
+ "version": "2.0.1",
4
4
  "description": "Core module for yumeri",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -34,7 +34,6 @@
34
34
  "typescript": "^5.8.2"
35
35
  },
36
36
  "dependencies": {
37
- "@yumerijs/loader": "^1.2.0",
38
37
  "chokidar": "^4.0.3",
39
38
  "formidable": "^3.5.4",
40
39
  "js-yaml": "^4.1.0",