@doracli/express 0.0.2 → 0.0.4

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/esm/index.js CHANGED
@@ -1,13 +1,51 @@
1
+ import path$1, { join } from 'path';
2
+ import { sleep, uri } from '@cclr/utils';
3
+ import { mkdirRecursionSync, isValidDirSync, cleanTargets, getCwd } from '@dorabag/file-pro';
1
4
  import express from 'express';
2
- import { getCwd } from '@dorabag/file-pro';
3
- import { set, get } from '@cclr/lang';
4
- import { cLog } from '@doracli/helper';
5
-
6
- var createServer = function createServer(config) {
7
- var app = express();
8
- return app;
9
- };
5
+ export { default as express } from 'express';
6
+ import { get, set, isFunction } from '@cclr/lang';
7
+ import crypto from 'crypto';
8
+ import { createReadStream, readFileSync, promises } from 'fs';
9
+ import zlib from 'zlib';
10
+ import { cLog, HtmlManage } from '@doracli/helper';
11
+ import path from 'node:path';
12
+ import { request as request$1 } from 'http';
13
+ import { request } from 'https';
14
+ import { URL } from 'url';
10
15
 
16
+ function _arrayLikeToArray(r, a) {
17
+ (null == a || a > r.length) && (a = r.length);
18
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
19
+ return n;
20
+ }
21
+ function _arrayWithHoles(r) {
22
+ if (Array.isArray(r)) return r;
23
+ }
24
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
25
+ try {
26
+ var i = n[a](c),
27
+ u = i.value;
28
+ } catch (n) {
29
+ return void e(n);
30
+ }
31
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
32
+ }
33
+ function _asyncToGenerator(n) {
34
+ return function () {
35
+ var t = this,
36
+ e = arguments;
37
+ return new Promise(function (r, o) {
38
+ var a = n.apply(t, e);
39
+ function _next(n) {
40
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
41
+ }
42
+ function _throw(n) {
43
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
44
+ }
45
+ _next(void 0);
46
+ });
47
+ };
48
+ }
11
49
  function _classCallCheck(a, n) {
12
50
  if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
13
51
  }
@@ -30,6 +68,33 @@ function _defineProperty(e, r, t) {
30
68
  writable: true
31
69
  }) : e[r] = t, e;
32
70
  }
71
+ function _iterableToArrayLimit(r, l) {
72
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
73
+ if (null != t) {
74
+ var e,
75
+ n,
76
+ i,
77
+ u,
78
+ a = [],
79
+ f = true,
80
+ o = false;
81
+ try {
82
+ if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
83
+ } catch (r) {
84
+ o = true, n = r;
85
+ } finally {
86
+ try {
87
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
88
+ } finally {
89
+ if (o) throw n;
90
+ }
91
+ }
92
+ return a;
93
+ }
94
+ }
95
+ function _nonIterableRest() {
96
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
97
+ }
33
98
  function ownKeys(e, r) {
34
99
  var t = Object.keys(e);
35
100
  if (Object.getOwnPropertySymbols) {
@@ -51,6 +116,117 @@ function _objectSpread2(e) {
51
116
  }
52
117
  return e;
53
118
  }
119
+ function _regenerator() {
120
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
121
+ var e,
122
+ t,
123
+ r = "function" == typeof Symbol ? Symbol : {},
124
+ n = r.iterator || "@@iterator",
125
+ o = r.toStringTag || "@@toStringTag";
126
+ function i(r, n, o, i) {
127
+ var c = n && n.prototype instanceof Generator ? n : Generator,
128
+ u = Object.create(c.prototype);
129
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
130
+ var i,
131
+ c,
132
+ u,
133
+ f = 0,
134
+ p = o || [],
135
+ y = false,
136
+ G = {
137
+ p: 0,
138
+ n: 0,
139
+ v: e,
140
+ a: d,
141
+ f: d.bind(e, 4),
142
+ d: function (t, r) {
143
+ return i = t, c = 0, u = e, G.n = r, a;
144
+ }
145
+ };
146
+ function d(r, n) {
147
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
148
+ var o,
149
+ i = p[t],
150
+ d = G.p,
151
+ l = i[2];
152
+ r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
153
+ }
154
+ if (o || r > 1) return a;
155
+ throw y = true, n;
156
+ }
157
+ return function (o, p, l) {
158
+ if (f > 1) throw TypeError("Generator is already running");
159
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
160
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
161
+ try {
162
+ if (f = 2, i) {
163
+ if (c || (o = "next"), t = i[o]) {
164
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
165
+ if (!t.done) return t;
166
+ u = t.value, c < 2 && (c = 0);
167
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
168
+ i = e;
169
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
170
+ } catch (t) {
171
+ i = e, c = 1, u = t;
172
+ } finally {
173
+ f = 1;
174
+ }
175
+ }
176
+ return {
177
+ value: t,
178
+ done: y
179
+ };
180
+ };
181
+ }(r, o, i), true), u;
182
+ }
183
+ var a = {};
184
+ function Generator() {}
185
+ function GeneratorFunction() {}
186
+ function GeneratorFunctionPrototype() {}
187
+ t = Object.getPrototypeOf;
188
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
189
+ return this;
190
+ }), t),
191
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
192
+ function f(e) {
193
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
194
+ }
195
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
196
+ return this;
197
+ }), _regeneratorDefine(u, "toString", function () {
198
+ return "[object Generator]";
199
+ }), (_regenerator = function () {
200
+ return {
201
+ w: i,
202
+ m: f
203
+ };
204
+ })();
205
+ }
206
+ function _regeneratorDefine(e, r, n, t) {
207
+ var i = Object.defineProperty;
208
+ try {
209
+ i({}, "", {});
210
+ } catch (e) {
211
+ i = 0;
212
+ }
213
+ _regeneratorDefine = function (e, r, n, t) {
214
+ function o(r, n) {
215
+ _regeneratorDefine(e, r, function (e) {
216
+ return this._invoke(r, n, e);
217
+ });
218
+ }
219
+ r ? i ? i(e, r, {
220
+ value: n,
221
+ enumerable: !t,
222
+ configurable: !t,
223
+ writable: !t
224
+ }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
225
+ }, _regeneratorDefine(e, r, n, t);
226
+ }
227
+ function _slicedToArray(r, e) {
228
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
229
+ }
54
230
  function _toPrimitive(t, r) {
55
231
  if ("object" != typeof t || !t) return t;
56
232
  var e = t[Symbol.toPrimitive];
@@ -59,12 +235,121 @@ function _toPrimitive(t, r) {
59
235
  if ("object" != typeof i) return i;
60
236
  throw new TypeError("@@toPrimitive must return a primitive value.");
61
237
  }
62
- return (String )(t);
238
+ return ("string" === r ? String : Number)(t);
63
239
  }
64
240
  function _toPropertyKey(t) {
65
241
  var i = _toPrimitive(t, "string");
66
242
  return "symbol" == typeof i ? i : i + "";
67
243
  }
244
+ function _unsupportedIterableToArray(r, a) {
245
+ if (r) {
246
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
247
+ var t = {}.toString.call(r).slice(8, -1);
248
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
249
+ }
250
+ }
251
+
252
+ var serverCacheMw = function serverCacheMw(cacheDir) {
253
+ return function (ctx) {
254
+ return function (next) {
255
+ return /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
256
+ var serverCacheDir;
257
+ return _regenerator().w(function (_context) {
258
+ while (1) switch (_context.n) {
259
+ case 0:
260
+ serverCacheDir = join(ctx.envParams.workRootDir, cacheDir || './.cache/serverCache');
261
+ if (!isValidDirSync(serverCacheDir)) {
262
+ _context.n = 3;
263
+ break;
264
+ }
265
+ _context.n = 1;
266
+ return cleanTargets(serverCacheDir);
267
+ case 1:
268
+ _context.n = 2;
269
+ return sleep(300);
270
+ case 2:
271
+ _context.n = 4;
272
+ break;
273
+ case 3:
274
+ mkdirRecursionSync(serverCacheDir);
275
+ case 4:
276
+ ctx.updateServerConfig({
277
+ cacheDir: serverCacheDir
278
+ });
279
+ return _context.a(2, next());
280
+ }
281
+ }, _callee);
282
+ }));
283
+ };
284
+ };
285
+ };
286
+
287
+ var envParamsMw = function envParamsMw(envParams) {
288
+ return function (ctx) {
289
+ return function (next) {
290
+ return /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
291
+ return _regenerator().w(function (_context) {
292
+ while (1) switch (_context.n) {
293
+ case 0:
294
+ ctx.updateEnvParams(envParams);
295
+ return _context.a(2, next());
296
+ }
297
+ }, _callee);
298
+ }));
299
+ };
300
+ };
301
+ };
302
+
303
+ var serverPlainMw = function serverPlainMw() {
304
+ return function (ctx) {
305
+ return function (next) {
306
+ return /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
307
+ var _ctx$configCtx$getDor, serviceConfig, _ref2, https, pathRouteMap, port, proxy;
308
+ return _regenerator().w(function (_context) {
309
+ while (1) switch (_context.n) {
310
+ case 0:
311
+ _ctx$configCtx$getDor = ctx.configCtx.getDoraConfig(), serviceConfig = _ctx$configCtx$getDor.serviceConfig;
312
+ _ref2 = serviceConfig, https = _ref2.https, pathRouteMap = _ref2.pathRouteMap, port = _ref2.port, proxy = _ref2.proxy;
313
+ ctx.updateServerConfig({
314
+ https: https,
315
+ pathRouteMap: pathRouteMap,
316
+ port: port,
317
+ proxy: proxy,
318
+ static: serviceConfig.static
319
+ });
320
+ return _context.a(2, next());
321
+ }
322
+ }, _callee);
323
+ }));
324
+ };
325
+ };
326
+ };
327
+
328
+ var serverScanMw = function serverScanMw(mainScan) {
329
+ return function (ctx) {
330
+ return function (next) {
331
+ return /*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
332
+ var _ctx$configCtx$getDor, serviceConfig, _ref2, scan;
333
+ return _regenerator().w(function (_context) {
334
+ while (1) switch (_context.n) {
335
+ case 0:
336
+ _ctx$configCtx$getDor = ctx.configCtx.getDoraConfig(), serviceConfig = _ctx$configCtx$getDor.serviceConfig;
337
+ _ref2 = serviceConfig, scan = _ref2.scan;
338
+ ctx.updateServerConfig({
339
+ scan: mainScan || scan
340
+ });
341
+ return _context.a(2, next());
342
+ }
343
+ }, _callee);
344
+ }));
345
+ };
346
+ };
347
+ };
348
+
349
+ var createServer = function createServer(config) {
350
+ var app = express();
351
+ return app;
352
+ };
68
353
 
69
354
  var RouteManager = /*#__PURE__*/function () {
70
355
  function RouteManager(app) {
@@ -75,23 +360,23 @@ var RouteManager = /*#__PURE__*/function () {
75
360
  }
76
361
  return _createClass(RouteManager, [{
77
362
  key: "check",
78
- value: function check(route) {
79
- return !!this.routesMap[route];
363
+ value: function check(route, method) {
364
+ return !!get(this.routesMap, "".concat(route, ".").concat(method));
80
365
  }
81
366
  }, {
82
367
  key: "add",
83
- value: function add(route, method, handler) {
84
- this.updateMap(route, method, handler);
368
+ value: function add(route, method, handler, options) {
369
+ this.updateMap(route, method, handler, 'added', options);
85
370
  this.app.route(route)[method](this.getProxyHandler(route, method));
86
371
  }
87
372
  }, {
88
373
  key: "update",
89
- value: function update(route, method, handler) {
90
- if (!this.check(route)) {
91
- this.add(route, method, handler);
374
+ value: function update(route, method, handler, options) {
375
+ if (!this.check(route, method)) {
376
+ this.add(route, method, handler, options);
92
377
  return;
93
378
  }
94
- this.updateMap(route, method, handler, 'updated');
379
+ this.updateMap(route, method, handler, 'updated', options);
95
380
  }
96
381
  }, {
97
382
  key: "remove",
@@ -110,23 +395,48 @@ var RouteManager = /*#__PURE__*/function () {
110
395
  key: "updateMap",
111
396
  value: function updateMap(route, method, handler) {
112
397
  var state = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'added';
398
+ var options = arguments.length > 4 ? arguments[4] : undefined;
113
399
  set(this.routesMap, "".concat(route, ".").concat(method), {
114
400
  state: state,
115
- handler: handler
401
+ handler: handler,
402
+ handlerType: options === null || options === void 0 ? void 0 : options.handlerType
116
403
  });
117
404
  }
118
405
  }, {
119
406
  key: "getProxyHandler",
120
407
  value: function getProxyHandler(route, method) {
121
408
  var _this = this;
122
- return function (req, res) {
123
- var record = get(_this.routesMap, "".concat(route, ".").concat(method), {});
124
- if (record.handler) {
125
- return record.handler(req, res);
126
- } else {
127
- return res.status(404).send("".concat(method, " ").concat(route, " route not found"));
128
- }
129
- };
409
+ return /*#__PURE__*/function () {
410
+ var _ref = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(req, res) {
411
+ var record, r;
412
+ return _regenerator().w(function (_context) {
413
+ while (1) switch (_context.n) {
414
+ case 0:
415
+ record = get(_this.routesMap, "".concat(route, ".").concat(method), {});
416
+ if (!record.handler) {
417
+ _context.n = 3;
418
+ break;
419
+ }
420
+ if (!(record.handlerType === 'REST')) {
421
+ _context.n = 2;
422
+ break;
423
+ }
424
+ _context.n = 1;
425
+ return record.handler(req, res);
426
+ case 1:
427
+ r = _context.v;
428
+ return _context.a(2, res.status(200).json(r));
429
+ case 2:
430
+ return _context.a(2, record.handler(req, res));
431
+ case 3:
432
+ return _context.a(2, res.status(404).send("".concat(method, " ").concat(route, " route not found")));
433
+ }
434
+ }, _callee);
435
+ }));
436
+ return function (_x, _x2) {
437
+ return _ref.apply(this, arguments);
438
+ };
439
+ }();
130
440
  }
131
441
  }]);
132
442
  }();
@@ -141,6 +451,7 @@ var Ctx = /*#__PURE__*/function () {
141
451
  scan: './',
142
452
  workRootDir: getCwd()
143
453
  });
454
+ _defineProperty(this, "serverConfig", {});
144
455
  this.configCtx = configCtx;
145
456
  this.app = app;
146
457
  this.routeManager = new RouteManager(app);
@@ -150,16 +461,300 @@ var Ctx = /*#__PURE__*/function () {
150
461
  value: function updateEnvParams(params) {
151
462
  this.envParams = _objectSpread2(_objectSpread2({}, this.envParams), params);
152
463
  }
464
+ }, {
465
+ key: "updateServerConfig",
466
+ value: function updateServerConfig(config) {
467
+ this.serverConfig = _objectSpread2(_objectSpread2({}, this.serverConfig), config);
468
+ }
469
+ }]);
470
+ }();
471
+
472
+ var fileListHtmlTemplate = "\n <html>\n <head>\n <title>File List</title>\n <style>\n .file-list {\n list-style: none;\n padding: 0;\n margin: 0;\n }\n </style>\n </head>\n <body>\n <h1>File List</h1>\n </body>\n </html>\n";
473
+
474
+ // mime.ts
475
+ var MIME_MAP = {
476
+ '.html': 'text/html; charset=utf-8',
477
+ '.htm': 'text/html; charset=utf-8',
478
+ '.css': 'text/css; charset=utf-8',
479
+ '.js': 'application/javascript; charset=utf-8',
480
+ '.mjs': 'application/javascript; charset=utf-8',
481
+ '.json': 'application/json; charset=utf-8',
482
+ '.png': 'image/png',
483
+ '.jpg': 'image/jpeg',
484
+ '.jpeg': 'image/jpeg',
485
+ '.gif': 'image/gif',
486
+ '.svg': 'image/svg+xml',
487
+ '.ico': 'image/x-icon',
488
+ '.webp': 'image/webp',
489
+ '.mp4': 'video/mp4',
490
+ '.webm': 'video/webm',
491
+ '.woff': 'font/woff',
492
+ '.woff2': 'font/woff2',
493
+ '.ttf': 'font/ttf',
494
+ '.otf': 'font/otf',
495
+ '.txt': 'text/plain; charset=utf-8',
496
+ '.xml': 'application/xml; charset=utf-8',
497
+ '.pdf': 'application/pdf'
498
+ };
499
+ var DEFAULT_MIME = 'application/octet-stream';
500
+ function getMimeType(filePath) {
501
+ var ext = path.extname(filePath).toLowerCase();
502
+ return MIME_MAP[ext] || DEFAULT_MIME;
503
+ }
504
+
505
+ var FileServer = /*#__PURE__*/function () {
506
+ function FileServer(directory, publicPath) {
507
+ _classCallCheck(this, FileServer);
508
+ this.directory = directory;
509
+ this.publicPath = publicPath;
510
+ _defineProperty(this, "htmlManage", new HtmlManage(HtmlManage.parseHtml(fileListHtmlTemplate)));
511
+ }
512
+
513
+ /**
514
+ * 请求入口
515
+ * @param {*} req
516
+ * @param {*} res
517
+ * @returns
518
+ */
519
+ return _createClass(FileServer, [{
520
+ key: "handleRequest",
521
+ value: (function () {
522
+ var _handleRequest = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(req, res) {
523
+ var pathname, requestFile, fsStat;
524
+ return _regenerator().w(function (_context) {
525
+ while (1) switch (_context.p = _context.n) {
526
+ case 0:
527
+ pathname = uri.getPathStr(req.url) || ''; // 过滤ico文件请求
528
+ if (!(pathname === '/favicon.ico')) {
529
+ _context.n = 1;
530
+ break;
531
+ }
532
+ return _context.a(2, res.send('no file !!'));
533
+ case 1:
534
+ // 整合参数
535
+ pathname = decodeURIComponent(pathname || '');
536
+ // pathname 去掉 publicPath
537
+ pathname = pathname.replace(this.publicPath, '');
538
+ requestFile = path$1.join(this.directory, pathname);
539
+ /** 设计允许跨域 */
540
+ res.setHeader('Access-Control-Allow-Origin', '*');
541
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
542
+ res.setHeader('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
543
+ res.setHeader('Content-Type', 'text/html;charset=utf-8');
544
+
545
+ // 判断路径属性,--路径 or 文件
546
+ _context.p = 2;
547
+ _context.n = 3;
548
+ return promises.stat(requestFile);
549
+ case 3:
550
+ fsStat = _context.v;
551
+ if (fsStat.isDirectory()) {
552
+ this.sendDir(requestFile, req, res);
553
+ } else {
554
+ this.sendFile(requestFile, req, res, fsStat);
555
+ }
556
+ _context.n = 5;
557
+ break;
558
+ case 4:
559
+ _context.p = 4;
560
+ _context.v;
561
+ cLog.error('fs', 'not_found', pathname);
562
+ res.send('File not found');
563
+ case 5:
564
+ return _context.a(2);
565
+ }
566
+ }, _callee, this, [[2, 4]]);
567
+ }));
568
+ function handleRequest(_x, _x2) {
569
+ return _handleRequest.apply(this, arguments);
570
+ }
571
+ return handleRequest;
572
+ }()
573
+ /**
574
+ * 相应文件路径数据
575
+ * @param {*} dirPath 文件目录路径
576
+ */
577
+ )
578
+ }, {
579
+ key: "sendDir",
580
+ value: (function () {
581
+ var _sendDir = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(dirPath, req, res) {
582
+ var dirList, pathname, fileContent;
583
+ return _regenerator().w(function (_context2) {
584
+ while (1) switch (_context2.n) {
585
+ case 0:
586
+ _context2.n = 1;
587
+ return promises.readdir(dirPath);
588
+ case 1:
589
+ dirList = _context2.v;
590
+ pathname = uri.getPathStr(req.url) || ''; // 生成返回模板数据
591
+ fileContent = this.htmlManage.copy().addBody({
592
+ tagName: 'ul',
593
+ attrs: [{
594
+ name: 'class',
595
+ value: 'file-list'
596
+ }],
597
+ children: dirList.map(function (dir) {
598
+ return {
599
+ tagName: 'li',
600
+ children: [{
601
+ tagName: 'a',
602
+ attrs: [{
603
+ name: 'href',
604
+ value: path$1.join(pathname, dir)
605
+ }],
606
+ children: [dir]
607
+ }]
608
+ };
609
+ })
610
+ }).generateHtml();
611
+ res.end(fileContent);
612
+ case 2:
613
+ return _context2.a(2);
614
+ }
615
+ }, _callee2, this);
616
+ }));
617
+ function sendDir(_x3, _x4, _x5) {
618
+ return _sendDir.apply(this, arguments);
619
+ }
620
+ return sendDir;
621
+ }()
622
+ /**
623
+ * 发送文件
624
+ * @param {*} requestFile
625
+ * @param {*} reqCtx 请求上下文
626
+ * @returns
627
+ */
628
+ )
629
+ }, {
630
+ key: "sendFile",
631
+ value: function sendFile(requestFile, req, res, fsStat) {
632
+ // 看缓存
633
+ if (this.cacheFile(req, res, requestFile, fsStat)) {
634
+ res.statusCode = 304;
635
+ return res.end();
636
+ }
637
+ // 返回文件时,配置请求头
638
+ res.setHeader('Content-Type', getMimeType(requestFile) + ';charset=utf-8');
639
+ var createGzip;
640
+ if (createGzip = this.gzipFile(req, res)) {
641
+ return createReadStream(requestFile).pipe(createGzip).pipe(res);
642
+ }
643
+ }
644
+ }, {
645
+ key: "cacheFile",
646
+ value: function cacheFile(req, res, requestFile, statObj) {
647
+ res.setHeader('Cache-Control', 'max-age=10000');
648
+ res.setHeader('Expires', new Date(Date.now() + 10 * 1000).toUTCString());
649
+ var lastMidfied = statObj.ctime.toUTCString();
650
+ var etag = crypto.createHash('md5').update(readFileSync(requestFile)).digest('base64');
651
+ res.setHeader('Last-Modified', lastMidfied);
652
+ res.setHeader('Etag', etag);
653
+ var ifModifiedSince = req.headers['if-modified-since'];
654
+ var ifNoneMatch = req.headers['if-none-match'];
655
+ if (lastMidfied !== ifModifiedSince) {
656
+ // console.log("最后修改时间不同");
657
+ return false;
658
+ }
659
+ if (ifNoneMatch !== etag) {
660
+ // console.log("文件不同");
661
+ return false;
662
+ }
663
+ return true;
664
+ }
153
665
 
154
- // getServiceConfig() {
155
- // return this.configCtx.getDoraConfig().serviceConfig!;
156
- // }
666
+ /**
667
+ * 文件压缩
668
+ * @param {*} req
669
+ * @param {*} res
670
+ * @returns
671
+ */
672
+ }, {
673
+ key: "gzipFile",
674
+ value: function gzipFile(req, res) {
675
+ var encodings = req.headers['accept-encoding'];
676
+ if (encodings) {
677
+ if (encodings.includes('gzip')) {
678
+ res.setHeader('Content-Encoding', 'gzip');
679
+ return zlib.createGzip();
680
+ } else if (encodings.includes('deflage')) {
681
+ res.setHeader('Content-Encoding', 'deflage');
682
+ return zlib.createDeflate();
683
+ }
684
+ }
685
+ return false;
686
+ }
157
687
  }]);
158
688
  }();
159
689
 
690
+ var fileServerMiddleware = function fileServerMiddleware(route, directory) {
691
+ var fileServer = new FileServer(directory, route);
692
+ return function (req, res, next) {
693
+ // 1. 判断是否是需要拦截的路径
694
+ var pathname = uri.getPathStr(req.url) || '';
695
+ if (pathname.startsWith(route)) {
696
+ fileServer.handleRequest(req, res);
697
+ } else {
698
+ next();
699
+ }
700
+ };
701
+ };
702
+
160
703
  var loggerMiddleware = function loggerMiddleware(req, res, next) {
161
704
  cLog.log('ser', 'request', "[".concat(req.method, "] ").concat(req.url));
162
705
  next();
163
706
  };
164
707
 
165
- export { Ctx, RouteManager, createServer, loggerMiddleware };
708
+ var proxyMiddleware = function proxyMiddleware(ctx) {
709
+ return function (req, res, next) {
710
+ var proxy = ctx.serverConfig.proxy;
711
+ var pathname = uri.getPathStr(req.url) || '';
712
+ var findProxyPath = Object.keys(proxy || {}).find(function (key) {
713
+ return pathname.startsWith(key);
714
+ });
715
+ if (!findProxyPath) {
716
+ return next();
717
+ }
718
+ var _proxy$findProxyPath = proxy[findProxyPath],
719
+ router = _proxy$findProxyPath.router,
720
+ headers = _proxy$findProxyPath.headers,
721
+ pathRewrite = _proxy$findProxyPath.pathRewrite;
722
+ var routerStr = isFunction(router) ? router() : router;
723
+
724
+ // 应用路径重写
725
+ var targetPath = pathname;
726
+ if (pathRewrite) {
727
+ for (var _i = 0, _Object$entries = Object.entries(pathRewrite); _i < _Object$entries.length; _i++) {
728
+ var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
729
+ pattern = _Object$entries$_i[0],
730
+ replacement = _Object$entries$_i[1];
731
+ targetPath = targetPath.replace(new RegExp(pattern), replacement);
732
+ }
733
+ }
734
+ // 解析目标 URL
735
+ var targetUrl = new URL(targetPath, routerStr);
736
+ var requestFn = targetUrl.protocol === 'https:' ? request : request$1;
737
+ cLog.log('ser', 'proxy', "".concat(pathname, " => ").concat(targetUrl));
738
+ var proxyReq = requestFn(targetUrl, {
739
+ method: req.method,
740
+ headers: _objectSpread2(_objectSpread2({}, req.headers), headers)
741
+ }, function (proxyRes) {
742
+ // 转发响应状态和头
743
+ res.writeHead(proxyRes.statusCode || 500, proxyRes.headers);
744
+ // 管道传输响应体
745
+ proxyRes.pipe(res);
746
+ });
747
+ proxyReq.on('error', function (err) {
748
+ cLog.debug('ser', 'proxy', err);
749
+ res.status(500).json({
750
+ message: err.message,
751
+ code: err.code
752
+ });
753
+ });
754
+
755
+ // 管道传输请求体
756
+ req.pipe(proxyReq);
757
+ };
758
+ };
759
+
760
+ export { Ctx, RouteManager, createServer, envParamsMw, fileServerMiddleware, loggerMiddleware, proxyMiddleware, serverCacheMw, serverPlainMw, serverScanMw };