k99 0.2.0 → 0.3.0-beta.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.
Files changed (154) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +8 -0
  3. package/README.zh.md +8 -0
  4. package/browser/package.json +8 -0
  5. package/browser/types.d.ts +20 -0
  6. package/cli/command/create.js +1 -2
  7. package/cli/command/index.js +1 -2
  8. package/cli/command/init.js +3 -5
  9. package/cli/command/start.js +9 -10
  10. package/cli/index.js +3 -4
  11. package/cli/opt/bind.js +1 -2
  12. package/cli/opt/index.js +1 -2
  13. package/cli/opt/listen.js +1 -2
  14. package/cli/opt/path.js +1 -2
  15. package/cli/opt/port.js +1 -2
  16. package/cli/opt/show-router.js +1 -2
  17. package/dist/k99.browser.js +3110 -0
  18. package/dist/k99.browser.min.js +6 -0
  19. package/dist/k99.esm.js +3082 -0
  20. package/dist/k99.esm.min.js +6 -0
  21. package/dist/k99.js +3104 -0
  22. package/dist/k99.mjs +3082 -0
  23. package/dist/k99Browser.browser.js +490 -0
  24. package/dist/k99Browser.browser.min.js +6 -0
  25. package/dist/k99Browser.esm.js +475 -0
  26. package/dist/k99Browser.esm.min.js +6 -0
  27. package/dist/k99Browser.js +484 -0
  28. package/dist/k99Browser.mjs +475 -0
  29. package/dist/k99Services.browser.js +145 -0
  30. package/dist/k99Services.browser.min.js +6 -0
  31. package/dist/k99Services.esm.js +136 -0
  32. package/dist/k99Services.esm.min.js +6 -0
  33. package/dist/k99Services.js +141 -0
  34. package/dist/k99Services.mjs +136 -0
  35. package/node/index.js +1386 -0
  36. package/node/index.mjs +1350 -0
  37. package/node/package.json +5 -0
  38. package/node/types.d.ts +166 -0
  39. package/package.json +77 -11
  40. package/services/package.json +8 -0
  41. package/services/types.d.ts +22 -0
  42. package/starter.js +0 -1
  43. package/types.d.ts +748 -0
  44. package/Container.d.ts +0 -92
  45. package/Container.js +0 -242
  46. package/Container.js.map +0 -1
  47. package/Controller/index.d.ts +0 -178
  48. package/Controller/index.js +0 -576
  49. package/Controller/index.js.map +0 -1
  50. package/Controller/patch/cookie.d.ts +0 -33
  51. package/Controller/patch/cookie.js +0 -168
  52. package/Controller/patch/cookie.js.map +0 -1
  53. package/Controller/patch/index.d.ts +0 -7
  54. package/Controller/patch/index.js +0 -26
  55. package/Controller/patch/index.js.map +0 -1
  56. package/Controller/patch/render.d.ts +0 -5
  57. package/Controller/patch/render.js +0 -24
  58. package/Controller/patch/render.js.map +0 -1
  59. package/ExitSignal.d.ts +0 -14
  60. package/ExitSignal.js +0 -29
  61. package/ExitSignal.js.map +0 -1
  62. package/Extension.d.ts +0 -56
  63. package/Extension.js +0 -93
  64. package/Extension.js.map +0 -1
  65. package/ExtensionContainer.d.ts +0 -55
  66. package/ExtensionContainer.js +0 -105
  67. package/ExtensionContainer.js.map +0 -1
  68. package/Plugin.d.ts +0 -52
  69. package/Plugin.js +0 -278
  70. package/Plugin.js.map +0 -1
  71. package/Preprocessor.d.ts +0 -86
  72. package/Preprocessor.js +0 -135
  73. package/Preprocessor.js.map +0 -1
  74. package/Router/assets.d.ts +0 -33
  75. package/Router/assets.js +0 -106
  76. package/Router/assets.js.map +0 -1
  77. package/Router/callback.d.ts +0 -9
  78. package/Router/callback.js +0 -152
  79. package/Router/callback.js.map +0 -1
  80. package/Router/extendsInterface.d.ts +0 -8
  81. package/Router/extendsInterface.js +0 -43
  82. package/Router/extendsInterface.js.map +0 -1
  83. package/Router/index.d.ts +0 -184
  84. package/Router/index.js +0 -615
  85. package/Router/index.js.map +0 -1
  86. package/Router/log.d.ts +0 -23
  87. package/Router/log.js +0 -120
  88. package/Router/log.js.map +0 -1
  89. package/Router/order.d.ts +0 -14
  90. package/Router/order.js +0 -71
  91. package/Router/order.js.map +0 -1
  92. package/Router/register.d.ts +0 -9
  93. package/Router/register.js +0 -252
  94. package/Router/register.js.map +0 -1
  95. package/Router/registerManager.d.ts +0 -22
  96. package/Router/registerManager.js +0 -102
  97. package/Router/registerManager.js.map +0 -1
  98. package/Router/scan.d.ts +0 -2
  99. package/Router/scan.js +0 -72
  100. package/Router/scan.js.map +0 -1
  101. package/Router/setHandleItem.d.ts +0 -3
  102. package/Router/setHandleItem.js +0 -94
  103. package/Router/setHandleItem.js.map +0 -1
  104. package/Router/settings.d.ts +0 -12
  105. package/Router/settings.js +0 -74
  106. package/Router/settings.js.map +0 -1
  107. package/Router/start.d.ts +0 -3
  108. package/Router/start.js +0 -270
  109. package/Router/start.js.map +0 -1
  110. package/Router/vars.d.ts +0 -10
  111. package/Router/vars.js +0 -40
  112. package/Router/vars.js.map +0 -1
  113. package/Service.d.ts +0 -12
  114. package/Service.js +0 -20
  115. package/Service.js.map +0 -1
  116. package/cli/command/create.d.ts +0 -7
  117. package/cli/command/create.js.map +0 -1
  118. package/cli/command/index.d.ts +0 -7
  119. package/cli/command/index.js.map +0 -1
  120. package/cli/command/init.d.ts +0 -6
  121. package/cli/command/init.js.map +0 -1
  122. package/cli/command/start.d.ts +0 -6
  123. package/cli/command/start.js.map +0 -1
  124. package/cli/index.d.ts +0 -2
  125. package/cli/index.js.map +0 -1
  126. package/cli/opt/bind.d.ts +0 -3
  127. package/cli/opt/bind.js.map +0 -1
  128. package/cli/opt/index.d.ts +0 -16
  129. package/cli/opt/index.js.map +0 -1
  130. package/cli/opt/listen.d.ts +0 -3
  131. package/cli/opt/listen.js.map +0 -1
  132. package/cli/opt/path.d.ts +0 -3
  133. package/cli/opt/path.js.map +0 -1
  134. package/cli/opt/port.d.ts +0 -3
  135. package/cli/opt/port.js.map +0 -1
  136. package/cli/opt/show-router.d.ts +0 -3
  137. package/cli/opt/show-router.js.map +0 -1
  138. package/index.d.ts +0 -354
  139. package/index.js +0 -155
  140. package/index.js.map +0 -1
  141. package/setOptions.d.ts +0 -12
  142. package/setOptions.js +0 -60
  143. package/setOptions.js.map +0 -1
  144. package/starter.d.ts +0 -2
  145. package/starter.js.map +0 -1
  146. package/symbols.d.ts +0 -13
  147. package/symbols.js +0 -31
  148. package/symbols.js.map +0 -1
  149. package/util/index.d.ts +0 -5
  150. package/util/index.js +0 -92
  151. package/util/index.js.map +0 -1
  152. package/util/stream.d.ts +0 -19
  153. package/util/stream.js +0 -66
  154. package/util/stream.js.map +0 -1
@@ -0,0 +1,3110 @@
1
+ /*!
2
+ * k99 v0.3.0-beta.1
3
+ * (c) 2019-2022 Fierflame
4
+ * @license MIT
5
+ */
6
+ (function (global, factory) {
7
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
8
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
9
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.k99 = {}));
10
+ }(this, (function (exports) { 'use strict';
11
+
12
+ /**
13
+ * 服务
14
+ */
15
+ class Service {
16
+ /**
17
+ * @warning 不要重载构造函数或者主动调用创建实例
18
+ */
19
+ constructor(context) {
20
+ this.context = context;
21
+ Object.defineProperties(this, Object.getOwnPropertyDescriptors(context));
22
+ }
23
+
24
+ /** 销毁时,会自动调用此方法销毁自动创建的容器 */
25
+ async destroy() {}
26
+
27
+ }
28
+
29
+ (function (_Service) {})(Service || (Service = {}));
30
+
31
+ var Service$1 = Service;
32
+
33
+ const returnSymbol = Symbol('return');
34
+ const catchSymbol = Symbol('catch');
35
+ const finallySymbol = Symbol('finally');
36
+ const dataSymbol = Symbol('data');
37
+ const initSymbol = Symbol('init');
38
+ const methodsSymbol = Symbol('methods');
39
+ const testSymbol = Symbol('test');
40
+ const optionsSymbol = Symbol('options');
41
+
42
+ function Handle(handle) {
43
+ return handle;
44
+ }
45
+ /** 处理函数定义 */
46
+
47
+ exports.Log = void 0;
48
+
49
+ (function (_Log) {})(exports.Log || (exports.Log = {}));
50
+
51
+ exports.Settings = void 0;
52
+
53
+ (function (_Settings) {})(exports.Settings || (exports.Settings = {}));
54
+
55
+ exports.Assets = void 0;
56
+
57
+ (function (_Assets) {})(exports.Assets || (exports.Assets = {}));
58
+
59
+ function _defineProperty(obj, key, value) {
60
+ if (key in obj) {
61
+ Object.defineProperty(obj, key, {
62
+ value: value,
63
+ enumerable: true,
64
+ configurable: true,
65
+ writable: true
66
+ });
67
+ } else {
68
+ obj[key] = value;
69
+ }
70
+
71
+ return obj;
72
+ }
73
+
74
+ /** 花括号开 */
75
+ const OPEN = '{';
76
+ /** 花括号关 */
77
+
78
+ const CLOSE = '}';
79
+ /** 正则匹配 */
80
+
81
+ const PATTERN = 3;
82
+ /** 名字 */
83
+
84
+ const NAME = 4;
85
+ /** 普通字符 */
86
+
87
+ const CHAR = 5;
88
+ /** 转义字符 */
89
+
90
+ const ESCAPED_CHAR = 6;
91
+ /** 数量修饰符 */
92
+
93
+ const MODIFIER = 7;
94
+
95
+ function getType$1(char) {
96
+ if (char === '{') {
97
+ return OPEN;
98
+ }
99
+
100
+ if (char === '}') {
101
+ return CLOSE;
102
+ }
103
+
104
+ if (char === '*' || char === '+' || char === '?') {
105
+ return MODIFIER;
106
+ }
107
+
108
+ return CHAR;
109
+ }
110
+
111
+ function isNameChar(c) {
112
+ return '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c === '_';
113
+ }
114
+
115
+ function* lexer(str) {
116
+ let i = 0;
117
+
118
+ while (i < str.length) {
119
+ const index = i;
120
+ const char = str[i++];
121
+
122
+ if (char === '\\') {
123
+ const ch = str[i++];
124
+ yield [ESCAPED_CHAR, index, ch];
125
+ continue;
126
+ }
127
+
128
+ if (char === ':') {
129
+ for (; i < str.length; i++) {
130
+ if (!isNameChar(str[i])) {
131
+ break;
132
+ }
133
+ }
134
+
135
+ if (index + 1 === i) {
136
+ yield [CHAR, i, char];
137
+ continue;
138
+ }
139
+
140
+ yield [NAME, index, str.substring(index + 1, i)];
141
+ continue;
142
+ }
143
+
144
+ if (char !== '(') {
145
+ yield [getType$1(char), index, char];
146
+ continue;
147
+ }
148
+
149
+ if (str[i] === '?') {
150
+ throw new TypeError(`Pattern cannot start with "?" at ${i}`);
151
+ }
152
+
153
+ let count = 1;
154
+ const pattern = ['(?:'];
155
+
156
+ while (i < str.length) {
157
+ const c = str[i++];
158
+ pattern.push(c);
159
+
160
+ if (c === '\\') {
161
+ pattern.push(str[i++]);
162
+ continue;
163
+ }
164
+
165
+ if (c === ')') {
166
+ count--;
167
+
168
+ if (count === 0) {
169
+ break;
170
+ }
171
+
172
+ continue;
173
+ }
174
+
175
+ if (c === '[') {
176
+ while (i < str.length) {
177
+ const c = str[i++];
178
+ pattern.push(c);
179
+
180
+ if (c === ']') {
181
+ break;
182
+ }
183
+
184
+ if (c !== '\\') {
185
+ continue;
186
+ }
187
+
188
+ pattern.push(str[i++]);
189
+ }
190
+
191
+ continue;
192
+ }
193
+
194
+ if (c !== '(') {
195
+ continue;
196
+ }
197
+
198
+ count++;
199
+ pattern.push('?:');
200
+
201
+ if (str[i] !== '?') {
202
+ continue;
203
+ }
204
+
205
+ i += 2;
206
+
207
+ if (str[i - 1] === ':') {
208
+ continue;
209
+ }
210
+
211
+ throw new TypeError(`Invalid pattern group at ${i - 2}`);
212
+ }
213
+
214
+ if (count) {
215
+ throw new TypeError(`Unterminated pattern at ${index}`);
216
+ }
217
+
218
+ if (!pattern.length) {
219
+ throw new TypeError(`Missing pattern at ${index}`);
220
+ }
221
+
222
+ yield [PATTERN, index, pattern.join('')];
223
+ }
224
+ }
225
+
226
+ function throwError([type, index, value]) {
227
+ switch (type) {
228
+ case OPEN:
229
+ case CLOSE:
230
+ throw new TypeError(`Unexpected token '${type}' at ${index}`);
231
+
232
+ case PATTERN:
233
+ throw new TypeError(`Unexpected pattern '(${value})' at ${index}`);
234
+
235
+ case NAME:
236
+ throw new TypeError(`Unexpected name ':${value}' at ${index}`);
237
+
238
+ case CHAR:
239
+ throw new TypeError(`Unexpected char '${value}' at ${index}`);
240
+
241
+ case ESCAPED_CHAR:
242
+ throw new TypeError(`Unexpected char '\\' at ${index}`);
243
+
244
+ case MODIFIER:
245
+ throw new TypeError(`Unexpected token '${value}' at ${index}`);
246
+ }
247
+ }
248
+
249
+ const prefixes = '-/.:';
250
+
251
+ function throwUnexpectedError() {
252
+ throw new TypeError('Unexpected end of input');
253
+ }
254
+
255
+ function* parse(tokens) {
256
+ let i = 0;
257
+
258
+ function get(type) {
259
+ const token = tokens[i];
260
+
261
+ if (!token) {
262
+ return undefined;
263
+ }
264
+
265
+ const [nextType,, value] = token;
266
+
267
+ if (nextType !== type) {
268
+ return undefined;
269
+ }
270
+
271
+ i++;
272
+ return value;
273
+ }
274
+
275
+ function getText() {
276
+ let result = '';
277
+
278
+ for (let token = tokens[i]; token; token = tokens[++i]) {
279
+ const [type,, value] = token;
280
+
281
+ if (CHAR === type) {
282
+ result += value;
283
+ } else if (ESCAPED_CHAR === type) {
284
+ result += value;
285
+ } else {
286
+ break;
287
+ }
288
+ }
289
+
290
+ return result;
291
+ }
292
+
293
+ const path = [];
294
+
295
+ while (i < tokens.length) {
296
+ const char = get(CHAR) || get(MODIFIER) || '';
297
+ const name = get(NAME);
298
+ const pattern = get(PATTERN);
299
+
300
+ if (name || pattern) {
301
+ let prefix = '';
302
+
303
+ if (char && prefixes.includes(char)) {
304
+ prefix = char;
305
+ } else if (char) {
306
+ path.push(char);
307
+ }
308
+
309
+ if (path.length) {
310
+ yield path.join('');
311
+ path.length = 0;
312
+ }
313
+
314
+ const modifier = get(MODIFIER) || '';
315
+ yield {
316
+ prefix,
317
+ name: name || '',
318
+ suffix: '',
319
+ pattern,
320
+ modifier
321
+ };
322
+ continue;
323
+ }
324
+
325
+ const value = char || get(ESCAPED_CHAR) || get(MODIFIER);
326
+
327
+ if (value) {
328
+ if (value !== '/') {
329
+ path.push(value);
330
+ continue;
331
+ }
332
+
333
+ if (path.length) {
334
+ yield path.join('');
335
+ path.length = 0;
336
+ }
337
+
338
+ yield '/';
339
+ continue;
340
+ }
341
+
342
+ if (path.length) {
343
+ yield path.join('');
344
+ path.length = 0;
345
+ }
346
+
347
+ const openToken = tokens[i++];
348
+
349
+ if (!openToken) {
350
+ break;
351
+ }
352
+
353
+ if (openToken[0] !== OPEN) {
354
+ throwError(openToken);
355
+ }
356
+
357
+ const prefix = getText();
358
+ const groupName = get(NAME) || '';
359
+ const groupPattern = get(PATTERN);
360
+ const suffix = getText();
361
+ const closeToken = tokens[i++];
362
+
363
+ if (!closeToken) {
364
+ throwUnexpectedError();
365
+ }
366
+
367
+ if (closeToken[0] !== CLOSE) {
368
+ throwError(closeToken);
369
+ }
370
+
371
+ const modifier = get(MODIFIER) || '';
372
+ yield {
373
+ prefix,
374
+ name: groupName || '',
375
+ pattern: groupPattern,
376
+ suffix,
377
+ modifier,
378
+ group: true
379
+ };
380
+ }
381
+
382
+ if (path.length) {
383
+ yield path.join('');
384
+ }
385
+ }
386
+
387
+ function isNewLine(token) {
388
+ if (token === '/') {
389
+ return true;
390
+ }
391
+
392
+ if (typeof token !== 'string' && token.prefix === '/') {
393
+ return true;
394
+ }
395
+
396
+ return false;
397
+ }
398
+
399
+ const dotRegex$1 = /^\.+$/;
400
+
401
+ function valid(paragraph) {
402
+ if (paragraph[0] !== '/') {
403
+ return true;
404
+ }
405
+
406
+ if (paragraph.length === 1) {
407
+ return false;
408
+ }
409
+
410
+ if (paragraph.length !== 2) {
411
+ return true;
412
+ }
413
+
414
+ const [, t] = paragraph;
415
+
416
+ if (typeof t !== 'string') {
417
+ return true;
418
+ }
419
+
420
+ if (!dotRegex$1.test(t)) {
421
+ return true;
422
+ }
423
+
424
+ return false;
425
+ }
426
+
427
+ function* clear(tokens) {
428
+ let paragraph = ['/'];
429
+
430
+ for (const token of tokens) {
431
+ if (isNewLine(token)) {
432
+ if (valid(paragraph)) {
433
+ yield* paragraph;
434
+ }
435
+
436
+ paragraph = [];
437
+ }
438
+
439
+ paragraph.push(token);
440
+ }
441
+
442
+ if (valid(paragraph)) {
443
+ yield* paragraph;
444
+ }
445
+ }
446
+
447
+ function toTokens(path) {
448
+ const lexTokens = [...lexer(path)];
449
+ const tokens = parse(lexTokens);
450
+ return [...clear(tokens)];
451
+ }
452
+
453
+ function escapeString(str) {
454
+ return decodeURIComponent(str).replace(/([.+*?=^!:${}()[\]|\\])/g, '\\$1');
455
+ }
456
+
457
+ function createSetFn({
458
+ name,
459
+ modifier,
460
+ suffix,
461
+ prefix
462
+ }) {
463
+ if (!['*', '+'].includes(modifier) || !prefix && !suffix) {
464
+ if (typeof name === 'number') {
465
+ return (p, s, k) => p[name + k] = decodeURIComponent(s);
466
+ }
467
+
468
+ return (p, s) => p[name] = decodeURIComponent(s);
469
+ }
470
+
471
+ const split = prefix + suffix;
472
+
473
+ if (typeof name === 'number') {
474
+ return (p, s, k) => {
475
+ p[name + k] = s.split(split).map(value => decodeURIComponent(value));
476
+ };
477
+ }
478
+
479
+ return (p, s) => {
480
+ p[name] = s.split(split).map(value => decodeURIComponent(value));
481
+ };
482
+ }
483
+
484
+ const defaultPattern = '[^/]+?';
485
+
486
+ function tokenToFragment(token, setFns) {
487
+ if (typeof token === 'string') {
488
+ return escapeString(token);
489
+ }
490
+
491
+ const prefix = escapeString(token.prefix);
492
+ const suffix = escapeString(token.suffix);
493
+ const {
494
+ name,
495
+ modifier
496
+ } = token;
497
+
498
+ if (name === '') {
499
+ return `(?:${prefix}${suffix})${modifier}`;
500
+ }
501
+
502
+ setFns.push(createSetFn(token));
503
+ const pattern = token.pattern || defaultPattern;
504
+
505
+ if (!prefix && !suffix) {
506
+ return `((?:${pattern})${modifier})`;
507
+ }
508
+
509
+ if (modifier === '?') {
510
+ return `(?:${prefix}(${pattern})${suffix})?`;
511
+ }
512
+
513
+ if (modifier === '+') {
514
+ return `${prefix}(${pattern}(?:${suffix}${prefix}${pattern})*)${suffix}`;
515
+ }
516
+
517
+ if (modifier === '*') {
518
+ return `(?:${prefix}(${pattern}(?:${suffix}${prefix}${pattern})*)${suffix})?`;
519
+ }
520
+
521
+ return `${prefix}(${pattern})${suffix}`;
522
+ }
523
+
524
+ function tokensToRegex(paramsSetters, tokens, end) {
525
+ const tokenRegex = tokens.map(t => tokenToFragment(t, paramsSetters));
526
+ tokenRegex.unshift('^');
527
+ tokenRegex.push(end ? '$' : '(?=/|$)');
528
+ return new RegExp(tokenRegex.join(''), 'i');
529
+ }
530
+
531
+ function setParams(paramsSetters, regexExecArray, key, path) {
532
+ const params = Object.create(null);
533
+
534
+ for (let i = 1; i < regexExecArray.length; i++) {
535
+ const v = regexExecArray[i];
536
+
537
+ if (v === undefined) {
538
+ continue;
539
+ }
540
+
541
+ const fn = paramsSetters[i];
542
+
543
+ if (!fn) {
544
+ continue;
545
+ }
546
+
547
+ fn(params, v, key);
548
+ }
549
+
550
+ params.$path = path;
551
+ return params;
552
+ }
553
+
554
+ function rootMatch(paramsSetters, re, path) {
555
+ const res = re.exec(path);
556
+
557
+ if (!res) {
558
+ return null;
559
+ }
560
+
561
+ return setParams(paramsSetters, res, 0, res[0]);
562
+ }
563
+
564
+ function backMatch(paramsSetters, re, path, parent, key = 0) {
565
+ const res = re.exec(path.substring(parent.length));
566
+
567
+ if (!res) {
568
+ return null;
569
+ }
570
+
571
+ return setParams(paramsSetters, res, key, `${parent}${res[0]}`);
572
+ }
573
+
574
+ function parentMatch(paramsSetters, re, depth, path, parentPath, key = 0) {
575
+ const paths = parentPath.split('/').filter(Boolean);
576
+
577
+ if (depth >= paths.length) {
578
+ return rootMatch(paramsSetters, re, path);
579
+ }
580
+
581
+ const basePath = `/${paths.splice(0, paths.length - depth).join('/')}`;
582
+ return backMatch(paramsSetters, re, path, basePath, key);
583
+ }
584
+
585
+ function appendMatch(paramsSetters, re, path, parent, key = 0) {
586
+ if (parent[parent.length - 1] === '/') {
587
+ parent = parent.substring(0, parent.length - 1);
588
+ }
589
+
590
+ return backMatch(paramsSetters, re, path, parent, key);
591
+ }
592
+
593
+ function setKey(tokens) {
594
+ let key = 0;
595
+
596
+ for (const token of tokens) {
597
+ if (typeof token === 'string') {
598
+ continue;
599
+ }
600
+
601
+ if (token.name) {
602
+ continue;
603
+ }
604
+
605
+ if (!token.pattern) {
606
+ continue;
607
+ }
608
+
609
+ token.name = key++;
610
+ }
611
+
612
+ return key;
613
+ }
614
+
615
+ const regex$1 = /^(\.+)\/+/;
616
+ function createMatch(path, end) {
617
+ if (!path || path === '*') {
618
+ const match = (_, parent) => ({
619
+ $path: parent
620
+ });
621
+
622
+ match.keyLen = 0;
623
+ return match;
624
+ }
625
+
626
+ if (path === '.') {
627
+ const match = (path, parent) => {
628
+ if (parent[parent.length - 1] === '/') {
629
+ parent = parent.substring(0, parent.length - 1);
630
+ }
631
+
632
+ const char = path[parent.length];
633
+
634
+ if (char && (char !== '/' || end && path.length - 1 > parent.length)) {
635
+ return null;
636
+ }
637
+
638
+ const params = Object.create(null);
639
+ params.$path = `${parent}${char}`;
640
+ return params;
641
+ };
642
+
643
+ match.keyLen = 0;
644
+ return match;
645
+ }
646
+
647
+ const isRoot = path[0] === '/';
648
+ let depth = 0;
649
+
650
+ for (let s = regex$1.exec(path); s; s = regex$1.exec(path)) {
651
+ const [{
652
+ length
653
+ }, {
654
+ length: len
655
+ }] = s;
656
+ path = path.substring(length);
657
+ depth += len - 1;
658
+ }
659
+
660
+ if (depth) {
661
+ path = `/${path}`;
662
+ }
663
+
664
+ const tokens = toTokens(path);
665
+ const key = setKey(tokens);
666
+ const paramsSetters = [() => {}];
667
+ const re = tokensToRegex(paramsSetters, tokens, end);
668
+
669
+ if (isRoot) {
670
+ const match = path => rootMatch(paramsSetters, re, path);
671
+
672
+ match.keyLen = key;
673
+ match.isRoot = true;
674
+ return match;
675
+ }
676
+
677
+ if (depth) {
678
+ const match = (...p) => parentMatch(paramsSetters, re, depth, ...p);
679
+
680
+ match.keyLen = key;
681
+ return match;
682
+ }
683
+
684
+ const match = (...p) => appendMatch(paramsSetters, re, ...p);
685
+
686
+ match.keyLen = key;
687
+ return match;
688
+ }
689
+
690
+ function getMethods(methods) {
691
+ if (typeof methods === 'string') {
692
+ return [methods];
693
+ }
694
+
695
+ if (Array.isArray(methods)) {
696
+ return methods;
697
+ }
698
+
699
+ return ['GET', 'POST', 'PUT', 'DELETE'];
700
+ }
701
+
702
+ function verb(routes, path, handle, options = {}) {
703
+ const methods = getMethods(options.methods || handle[methodsSymbol]);
704
+
705
+ if (!methods.length) {
706
+ return null;
707
+ }
708
+
709
+ const {
710
+ controller,
711
+ test = handle[testSymbol],
712
+ plugin = '',
713
+ root = '',
714
+ absPath = '',
715
+ filePath = '',
716
+ name = handle.name
717
+ } = options;
718
+ const route = {
719
+ controller,
720
+ root,
721
+ absPath,
722
+ filePath,
723
+ handle,
724
+ plugin,
725
+ path: path.replace(/(.)\/+$/, '$1').replace(/\/+/g, '/'),
726
+ methods,
727
+ test,
728
+ name,
729
+ match: createMatch(path, true)
730
+ };
731
+ routes.push(route);
732
+ return route;
733
+ }
734
+
735
+ /** 方法列表 */
736
+
737
+ const methods = new Set(['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS']);
738
+
739
+ function setHandles(routes, path, handles, opt, name = '') {
740
+ for (const method of methods) {
741
+ const fn = handles[method];
742
+
743
+ if (typeof fn !== 'function') {
744
+ continue;
745
+ }
746
+
747
+ verb(routes, path, fn, { ...opt,
748
+ test: fn[testSymbol] || handles[testSymbol],
749
+ methods: [method],
750
+ name: name || method
751
+ });
752
+ }
753
+ }
754
+
755
+ function setHandle(routes, path, item, opt, name = '') {
756
+ const options = { ...opt
757
+ };
758
+ delete options.test;
759
+ delete options.methods;
760
+ const route = verb(routes, path, item, { ...options,
761
+ name
762
+ });
763
+
764
+ if (!route) {
765
+ return;
766
+ }
767
+
768
+ if (route.methods.includes('OPTIONS')) {
769
+ return;
770
+ }
771
+
772
+ let {
773
+ controller,
774
+ test,
775
+ plugin = '',
776
+ root = '',
777
+ absPath = '',
778
+ filePath = ''
779
+ } = opt || {};
780
+ path = path.replace(/(.)\/+$/, '$1').replace(/\/+/g, '/');
781
+ routes.push({
782
+ controller,
783
+ root,
784
+ absPath,
785
+ filePath,
786
+ handle: optionsSymbol,
787
+ plugin,
788
+ path,
789
+ methods: ['OPTIONS'],
790
+ test,
791
+ name: `${name}:OPTIONS`,
792
+ match: createMatch(path, true)
793
+ });
794
+ }
795
+
796
+ function setHandleItem(routes, path, item, opt, name = '') {
797
+ if (!item) {
798
+ return;
799
+ }
800
+
801
+ if (typeof item === 'object') {
802
+ setHandles(routes, path, item, opt, name);
803
+ } else if (typeof item === 'function') {
804
+ setHandle(routes, path, item, opt, name);
805
+ }
806
+ }
807
+
808
+ function initOptions(routes, exports, {
809
+ controller,
810
+ plugin,
811
+ root,
812
+ filePath,
813
+ absPath
814
+ } = {}) {
815
+ // 公共选项
816
+ const options = {
817
+ controller: exports.Controller || controller,
818
+ plugin,
819
+ root,
820
+ filePath,
821
+ absPath
822
+ }; // 将自身添加到路由
823
+
824
+ setHandleItem(routes, '', exports, options);
825
+ return options;
826
+ }
827
+
828
+ /** 资源的处理函数配置 */
829
+
830
+ const resourceHandleMap = {
831
+ index: {
832
+ methods: ['GET'],
833
+ path: ''
834
+ },
835
+ create: {
836
+ methods: ['POST'],
837
+ path: ''
838
+ },
839
+ new: {
840
+ methods: ['GET'],
841
+ path: 'new'
842
+ },
843
+ show: {
844
+ methods: ['GET'],
845
+ path: ':id'
846
+ },
847
+ update: {
848
+ methods: ['PUT'],
849
+ path: ':id'
850
+ },
851
+ destroy: {
852
+ methods: ['DELETE'],
853
+ path: ':id'
854
+ }
855
+ };
856
+ function setResource(routes, exports, options) {
857
+ options = initOptions(routes, exports, options);
858
+
859
+ for (const k in exports) {
860
+ const item = exports[k];
861
+
862
+ if (!item) {
863
+ continue;
864
+ }
865
+
866
+ if (!/^[a-z0-9][a-z0-9A-Z_-]*$/.test(k)) {
867
+ continue;
868
+ } // 特定处理处理函数
869
+
870
+
871
+ if (typeof item === 'function' && k in resourceHandleMap) {
872
+ const info = resourceHandleMap[k];
873
+ verb(routes, info.path, item, { ...options,
874
+ test: item[testSymbol],
875
+ methods: info.methods,
876
+ name: k
877
+ });
878
+ continue;
879
+ } // 成员处理函数
880
+
881
+
882
+ setHandleItem(routes, `:id/${k}`, item, options, k);
883
+ }
884
+ }
885
+
886
+ /**
887
+ * 处理器
888
+ */
889
+
890
+ class Controller {
891
+ static isControllerConstructor(v) {
892
+ if (v === Controller) {
893
+ return true;
894
+ }
895
+
896
+ if (typeof v !== 'function') {
897
+ return false;
898
+ }
899
+
900
+ return Controller.isPrototypeOf(v);
901
+ }
902
+
903
+ /**
904
+ * @warning 不要重载构造函数或者主动调用创建实例
905
+ */
906
+ constructor(context) {
907
+ this.context = context;
908
+ Object.defineProperties(this, Object.getOwnPropertyDescriptors(context));
909
+ }
910
+ /**
911
+ * 初始化
912
+ * @description 如果有初始化操作,应当在 init 中实现
913
+ * @description 此方法由路由调用
914
+ */
915
+
916
+
917
+ [initSymbol]() {}
918
+ /** 处理函数的第一个参数 */
919
+
920
+
921
+ [dataSymbol]() {
922
+ const data = { ...this.query
923
+ };
924
+ const {
925
+ body
926
+ } = this;
927
+
928
+ if (body && typeof body === 'object') {
929
+ Object.assign(data, body);
930
+ }
931
+
932
+ Object.assign(data, this.params);
933
+ return data;
934
+ }
935
+ /**
936
+ * OPTIONS 的默认处理函数
937
+ * @description 如果需要,则需要在此函数中实现
938
+ * @description 当已 OPTIONS 方法请求资源,且资源对应的路径中没有定义 OPTIONS 方法处理是的处理函数
939
+ */
940
+
941
+
942
+ [optionsSymbol]() {}
943
+ /**
944
+ * 对处理函数的结果进行处理
945
+ * @description 如果需要自定义处理,需要重载此方法
946
+ * @description 此方法由路由调用
947
+ * @param result 处理函数的结果
948
+ */
949
+
950
+
951
+ [returnSymbol](result) {
952
+ return this.write(result).then(e => {
953
+ if (e) {
954
+ return;
955
+ }
956
+
957
+ if (typeof result !== 'object') {
958
+ return;
959
+ }
960
+
961
+ this.responseType = 'application/json';
962
+ return this.write(JSON.stringify(result));
963
+ }).then(() => {});
964
+ }
965
+ /**
966
+ * 处理完成后,实例销毁前,如果有错误未被处理,将回交由此参数处理
967
+ * @description 如果需要自定义处理,需要重载此方法
968
+ * @description 此方法由路由调用
969
+ */
970
+
971
+
972
+ [catchSymbol](e) {
973
+ return this.logs.error(e).then(() => {});
974
+ }
975
+ /**
976
+ * 处理完成后,实例即将销毁时的处理函数
977
+ * @description 如果有销毁操作,应当在 finally 中通过实现
978
+ * @description 此方法由 destroy 调用
979
+ */
980
+
981
+
982
+ [finallySymbol]() {}
983
+
984
+ }
985
+
986
+ (function (_Controller) {})(Controller || (Controller = {}));
987
+
988
+ var Controller$1 = Controller;
989
+
990
+ function setControllerResource(routes, controller, {
991
+ plugin = '',
992
+ root = '',
993
+ absPath = '',
994
+ filePath = ''
995
+ } = {}) {
996
+ const {
997
+ prototype
998
+ } = controller;
999
+
1000
+ for (const k in prototype) {
1001
+ if (typeof prototype[k] !== 'function') {
1002
+ continue;
1003
+ }
1004
+
1005
+ if (!/^[a-z0-9][a-z0-9A-Z_-]*$/.test(k)) {
1006
+ continue;
1007
+ } // 特定处理处理函数
1008
+
1009
+
1010
+ let path = k.replace(/(.)\/+$/, '$1').replace(/\/+/g, '/');
1011
+ let methods = ['GET', 'POST', 'PUT', 'DELETE'];
1012
+
1013
+ if (k in resourceHandleMap) {
1014
+ const info = resourceHandleMap[k];
1015
+ path = info.path ? `${info.path}` : '';
1016
+ ({
1017
+ methods
1018
+ } = info);
1019
+ }
1020
+
1021
+ routes.push({
1022
+ controller,
1023
+ root,
1024
+ absPath,
1025
+ filePath,
1026
+ handle: k,
1027
+ plugin,
1028
+ path,
1029
+ methods,
1030
+ name: k,
1031
+ match: createMatch(path, true)
1032
+ });
1033
+ }
1034
+ }
1035
+
1036
+ class Router {
1037
+ /** 路由列表 */
1038
+ constructor(path = '') {
1039
+ _defineProperty(this, "disabled", false);
1040
+
1041
+ _defineProperty(this, "__routes", []);
1042
+
1043
+ _defineProperty(this, "guards", new Set());
1044
+
1045
+ path = path.replace(/(.)\/+$/, '$1').replace(/\/+/g, '/');
1046
+ this.path = path;
1047
+ this.match = createMatch(path, false);
1048
+ }
1049
+ /** 子路由 */
1050
+
1051
+
1052
+ route(path) {
1053
+ const router = path instanceof Router ? path : new Router(path);
1054
+
1055
+ this.__routes.push(router);
1056
+
1057
+ return router;
1058
+ }
1059
+
1060
+ verb(path, handle, methods, options) {
1061
+ if (typeof handle !== 'function') {
1062
+ return this;
1063
+ }
1064
+
1065
+ if (typeof methods === 'string') {
1066
+ verb(this.__routes, path, handle, { ...options,
1067
+ methods: [methods]
1068
+ });
1069
+ } else if (Array.isArray(methods)) {
1070
+ verb(this.__routes, path, handle, { ...options,
1071
+ methods
1072
+ });
1073
+ } else {
1074
+ verb(this.__routes, path, handle, methods);
1075
+ }
1076
+
1077
+ return this;
1078
+ }
1079
+ /**
1080
+ * 注册 HTTP GET 处理函数
1081
+ * @param path 要注册的路径
1082
+ * @param handle 要注册的处理函数
1083
+ * @param options 选项
1084
+ */
1085
+
1086
+
1087
+ get(path, handle, options) {
1088
+ if (typeof handle !== 'function') {
1089
+ return this;
1090
+ }
1091
+
1092
+ verb(this.__routes, path, handle, { ...options,
1093
+ methods: ['GET']
1094
+ });
1095
+ return this;
1096
+ }
1097
+ /**
1098
+ * 注册 HTTP POST 处理函数
1099
+ * @param path 要注册的路径
1100
+ * @param handle 要注册的处理函数
1101
+ * @param options 选项
1102
+ */
1103
+
1104
+
1105
+ post(path, handle, options) {
1106
+ if (typeof handle !== 'function') {
1107
+ return this;
1108
+ }
1109
+
1110
+ verb(this.__routes, path, handle, { ...options,
1111
+ methods: ['POST']
1112
+ });
1113
+ return this;
1114
+ }
1115
+ /**
1116
+ * 注册 HTTP PUT 处理函数
1117
+ * @param path 要注册的路径
1118
+ * @param handle 要注册的处理函数
1119
+ * @param options 选项
1120
+ */
1121
+
1122
+
1123
+ put(path, handle, options) {
1124
+ if (typeof handle !== 'function') {
1125
+ return this;
1126
+ }
1127
+
1128
+ verb(this.__routes, path, handle, { ...options,
1129
+ methods: ['PUT']
1130
+ });
1131
+ return this;
1132
+ }
1133
+ /**
1134
+ * 注册 HTTP DELETE 处理函数
1135
+ * @param path 要注册的路径
1136
+ * @param handle 要注册的处理函数
1137
+ * @param options 选项
1138
+ */
1139
+
1140
+
1141
+ delete(path, handle, options) {
1142
+ if (typeof handle !== 'function') {
1143
+ return this;
1144
+ }
1145
+
1146
+ verb(this.__routes, path, handle, { ...options,
1147
+ methods: ['DELETE']
1148
+ });
1149
+ return this;
1150
+ }
1151
+ /**
1152
+ * 注册 HTTP HEAD 处理函数
1153
+ * @param path 要注册的路径
1154
+ * @param handle 要注册的处理函数
1155
+ * @param options 选项
1156
+ */
1157
+
1158
+
1159
+ head(path, handle, options) {
1160
+ if (typeof handle !== 'function') {
1161
+ return this;
1162
+ }
1163
+
1164
+ verb(this.__routes, path, handle, { ...options,
1165
+ methods: ['HEAD']
1166
+ });
1167
+ return this;
1168
+ }
1169
+ /**
1170
+ * 注册 HTTP OPTIONS 处理函数
1171
+ * @param path 要注册的路径
1172
+ * @param handle 要注册的处理函数
1173
+ * @param options 选项
1174
+ */
1175
+
1176
+
1177
+ options(path, handle, options) {
1178
+ if (typeof handle !== 'function') {
1179
+ return this;
1180
+ }
1181
+
1182
+ verb(this.__routes, path, handle, { ...options,
1183
+ methods: ['OPTIONS']
1184
+ });
1185
+ return this;
1186
+ }
1187
+ /**
1188
+ * 注册 HTTP 资源
1189
+ * @param exports 要注册的资源
1190
+ * @param options 选项
1191
+ */
1192
+
1193
+
1194
+ resource(exports, options) {
1195
+ setResource(this.__routes, exports, options);
1196
+ return this;
1197
+ }
1198
+
1199
+ register(exports, options) {
1200
+ if (Controller$1.isControllerConstructor(exports)) {
1201
+ setControllerResource(this.__routes, exports, options);
1202
+ return this;
1203
+ }
1204
+
1205
+ if (Controller$1.isControllerConstructor(exports.default)) {
1206
+ setControllerResource(this.__routes, exports.default, options);
1207
+ return this;
1208
+ }
1209
+
1210
+ setResource(this.__routes, exports, options);
1211
+ return this;
1212
+ }
1213
+ /**
1214
+ * 注册 HTTP 处理函数集
1215
+ * @param exports 要注册的处理函数集
1216
+ * @param options 选项
1217
+ */
1218
+
1219
+
1220
+ collection(exports, options) {
1221
+ options = initOptions(this.__routes, exports, options);
1222
+
1223
+ for (const k in exports) {
1224
+ if (!/^[a-z0-9][a-z0-9A-Z_-]*$/.test(k)) {
1225
+ continue;
1226
+ }
1227
+
1228
+ setHandleItem(this.__routes, k, exports[k], options, k);
1229
+ }
1230
+
1231
+ return this;
1232
+ }
1233
+ /**
1234
+ * 注册 HTTP 资源成员处理函数集
1235
+ * @param exports 要注册的处理函数集
1236
+ * @param options 选项
1237
+ */
1238
+
1239
+
1240
+ member(exports, options) {
1241
+ options = initOptions(this.__routes, exports, options);
1242
+
1243
+ for (const k in exports) {
1244
+ if (!/^[a-z0-9][a-z0-9A-Z_-]*$/.test(k)) {
1245
+ continue;
1246
+ }
1247
+
1248
+ setHandleItem(this.__routes, `:id/${k}`, exports[k], options);
1249
+ }
1250
+
1251
+ return this;
1252
+ }
1253
+
1254
+ }
1255
+
1256
+ /**
1257
+ * 路由卫士
1258
+ * @description 用于路由的过滤及处理函数执行前的预处理
1259
+ */
1260
+ class Guard extends Service$1 {
1261
+ decide() {
1262
+ return true;
1263
+ }
1264
+ /**
1265
+ * 测试请求是否允许通过此路由访问
1266
+ * @description 同一请求、同一路径下,在此函数中调用的 this.set、this.get、this.delete、this.has、this.keys、this.clear 等方法的数据与实例初始化后的共享。目前不同路径下暂不共享,后续可能会被设计为共享,但不同请求下必然不共享
1267
+ * @description 同一路径下,若存在任意 test 返回 false 均会使得此路径不会被执行
1268
+ * @param param 请求参数
1269
+ */
1270
+
1271
+
1272
+ static async test(param) {
1273
+ return true;
1274
+ }
1275
+ /**
1276
+ * @description 映射的 Map 实例的 set 方法,与同一请求同一路径下的 test 共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1277
+ */
1278
+
1279
+
1280
+ set(k, v) {
1281
+ return this;
1282
+ }
1283
+ /**
1284
+ * @description 映射的 Map 实例的 get 方法,与同一请求同一路径下的 test 共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1285
+ */
1286
+
1287
+
1288
+ get(k) {
1289
+ return undefined;
1290
+ }
1291
+ /**
1292
+ * @description 映射的 Map 实例的 delete 方法,与同一请求同一路径下的 test 共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1293
+ */
1294
+
1295
+
1296
+ delete(k) {
1297
+ return false;
1298
+ }
1299
+ /**
1300
+ * @description 映射的 Map 实例的 has 方法,与同一请求同一路径下的 test 共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1301
+ */
1302
+
1303
+
1304
+ has(k) {
1305
+ return false;
1306
+ }
1307
+ /**
1308
+ * @description 映射的 Map 实例的 keys 方法,与同一请求同一路径下的 test 共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1309
+ */
1310
+
1311
+
1312
+ *keys() {}
1313
+ /**
1314
+ * @description 映射的 Map 实例的 clear 方法,与同一请求同一路径下的 test 共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1315
+ */
1316
+
1317
+
1318
+ clear() {}
1319
+ /**
1320
+ * @description 映射的 Map 实例的 size 属性,与同一请求同一路径下的 test 共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1321
+ */
1322
+
1323
+
1324
+ get size() {
1325
+ return 0;
1326
+ }
1327
+ /**
1328
+ * @description 映射的 Map 实例的 set 方法,与同一请求同一路径下的 Guard 实例共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1329
+ */
1330
+
1331
+
1332
+ static set(k, v) {
1333
+ return this;
1334
+ }
1335
+ /**
1336
+ * @description 映射的 Map 实例的 get 方法,与同一请求同一路径下的 Guard 实例共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1337
+ */
1338
+
1339
+
1340
+ static get(k) {
1341
+ return undefined;
1342
+ }
1343
+ /**
1344
+ * @description 映射的 Map 实例的 delete 方法,与同一请求同一路径下的 Guard 实例共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1345
+ */
1346
+
1347
+
1348
+ static delete(k) {
1349
+ return false;
1350
+ }
1351
+ /**
1352
+ * @description 映射的 Map 实例的 has 方法,与同一请求同一路径下的 Guard 实例共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1353
+ */
1354
+
1355
+
1356
+ static has(k) {
1357
+ return false;
1358
+ }
1359
+ /**
1360
+ * @description 映射的 Map 实例的 keys 方法,与同一请求同一路径下的 Guard 实例共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1361
+ */
1362
+
1363
+
1364
+ static *keys() {}
1365
+ /**
1366
+ * @description 映射的 Map 实例的 clear 方法,与同一请求同一路径下的 Guard 实例共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1367
+ */
1368
+
1369
+
1370
+ static clear() {}
1371
+ /**
1372
+ * @description 映射的 Map 实例的 size 属性,与同一请求同一路径下的 Guard 实例共享同一 Map 实例,此方法会在其他地方重载,常规方式重载无效
1373
+ */
1374
+
1375
+
1376
+ static get size() {
1377
+ return 0;
1378
+ }
1379
+
1380
+ }
1381
+
1382
+ (function (_Guard) {})(Guard || (Guard = {}));
1383
+
1384
+ var Guard$1 = Guard;
1385
+
1386
+ class ExitSignal extends Error {
1387
+ /**
1388
+ * 忽略对退出信号的捕获
1389
+ * @description 用于 try { } catch(e) {} 的 catch 中忽略退出信号
1390
+ * @example
1391
+ * try {
1392
+ * doSomething();
1393
+ * } catch (e) {
1394
+ * ExitSignal.assert(e);
1395
+ * customProcess(e);
1396
+ * }
1397
+ */
1398
+ static assert(v) {
1399
+ if (v instanceof ExitSignal) {
1400
+ throw v;
1401
+ }
1402
+ }
1403
+
1404
+ }
1405
+
1406
+ class Plugin {
1407
+ /** 包名 */
1408
+
1409
+ /** 版本 */
1410
+
1411
+ /** 作者 */
1412
+
1413
+ /** 开源协议 */
1414
+ constructor(name,
1415
+ /** 版本 */
1416
+ version, {
1417
+ author,
1418
+ license
1419
+ } = {}) {
1420
+ this.name = name;
1421
+ this.version = typeof version === 'string' ? version : '';
1422
+ this.author = typeof author === 'string' ? author : '';
1423
+ this.license = typeof license === 'string' ? license : '';
1424
+ }
1425
+
1426
+ _initRouter(router) {}
1427
+
1428
+ initRouter() {
1429
+ if (this.__initRouterPromise) {
1430
+ return this.__initRouterPromise;
1431
+ }
1432
+
1433
+ const {
1434
+ router
1435
+ } = this;
1436
+ return this.__initRouterPromise = Promise.resolve().then(() => this._initRouter(router)).then(() => router);
1437
+ }
1438
+
1439
+ get router() {
1440
+ const router = new Router();
1441
+ Reflect.defineProperty(this, 'router', {
1442
+ value: router,
1443
+ configurable: true
1444
+ });
1445
+ this.initRouter();
1446
+ return router;
1447
+ }
1448
+
1449
+ get disabled() {
1450
+ return this.router.disabled;
1451
+ }
1452
+
1453
+ set disabled(t) {
1454
+ this.router.disabled = t;
1455
+ }
1456
+
1457
+ }
1458
+
1459
+ function relateMap(obj, maps, key) {
1460
+ let map = maps.get(key);
1461
+
1462
+ if (!map) {
1463
+ map = new Map();
1464
+ maps.set(key, map);
1465
+ }
1466
+
1467
+ Object.defineProperties(obj, {
1468
+ set: {
1469
+ configurable: true,
1470
+
1471
+ value(k, v) {
1472
+ map.set(k, v);
1473
+ return this;
1474
+ }
1475
+
1476
+ },
1477
+ get: {
1478
+ configurable: true,
1479
+ value: k => map.get(k)
1480
+ },
1481
+ delete: {
1482
+ configurable: true,
1483
+ value: k => map.delete(k)
1484
+ },
1485
+ has: {
1486
+ configurable: true,
1487
+ value: k => map.has(k)
1488
+ },
1489
+ keys: {
1490
+ configurable: true,
1491
+ value: () => map.keys()
1492
+ },
1493
+ clear: {
1494
+ configurable: true,
1495
+ value: () => map.clear()
1496
+ },
1497
+ size: {
1498
+ configurable: true,
1499
+ get: () => map.size
1500
+ }
1501
+ });
1502
+ return obj;
1503
+ }
1504
+
1505
+ async function preprocess(guards, data, params) {
1506
+ for (let p of guards) {
1507
+ const pClass = relateMap(Object.create(p), data, p);
1508
+
1509
+ try {
1510
+ if (!(await pClass.test(params))) {
1511
+ return false;
1512
+ }
1513
+ } catch {
1514
+ return false;
1515
+ }
1516
+ }
1517
+
1518
+ return true;
1519
+ }
1520
+
1521
+ function methodVerify(methods, method) {
1522
+ if (!methods.length) {
1523
+ return true;
1524
+ }
1525
+
1526
+ if (methods.includes(method)) {
1527
+ return true;
1528
+ }
1529
+
1530
+ return false;
1531
+ }
1532
+
1533
+ async function runTest({
1534
+ test
1535
+ }, params) {
1536
+ if (typeof test !== 'function') {
1537
+ return true;
1538
+ } // 有效性验证
1539
+
1540
+
1541
+ try {
1542
+ return await test(params);
1543
+ } catch {
1544
+ return false;
1545
+ }
1546
+ }
1547
+
1548
+ async function matchRoute(route, method, path, baseParams, parentPath, key) {
1549
+ if (!methodVerify(route.methods, method)) {
1550
+ return null;
1551
+ }
1552
+
1553
+ const {
1554
+ match
1555
+ } = route;
1556
+ const result = match(path, parentPath, key);
1557
+
1558
+ if (!result) {
1559
+ return null;
1560
+ }
1561
+
1562
+ const params = match.isRoot ? result : { ...baseParams,
1563
+ ...result
1564
+ };
1565
+
1566
+ if (false === (await runTest(route, params))) {
1567
+ return null;
1568
+ }
1569
+
1570
+ return params;
1571
+ }
1572
+
1573
+ async function find(router, method, path, throughData, baseParams, routers, parentPath, key) {
1574
+ if (router.disabled) {
1575
+ return null;
1576
+ }
1577
+
1578
+ const {
1579
+ match
1580
+ } = router;
1581
+ const result = match(path, parentPath, key);
1582
+
1583
+ if (!result) {
1584
+ return null;
1585
+ }
1586
+
1587
+ const params = match.isRoot ? result : { ...baseParams,
1588
+ ...result
1589
+ }; // 预处理
1590
+
1591
+ if (!preprocess([...router.guards], throughData, params)) {
1592
+ return null;
1593
+ }
1594
+
1595
+ const newRouters = [...routers, router];
1596
+ const keyLen = match.isRoot ? match.keyLen : match.keyLen + key;
1597
+ const thisPath = result.$path;
1598
+
1599
+ for (const item of Array.from(router.__routes)) {
1600
+ if (item instanceof Router) {
1601
+ const res = await find(item, method, path, throughData, params, newRouters, thisPath, keyLen);
1602
+
1603
+ if (res) {
1604
+ return res;
1605
+ }
1606
+
1607
+ continue;
1608
+ }
1609
+
1610
+ const pathParams = await matchRoute(item, method, path, params, thisPath, keyLen);
1611
+
1612
+ if (!pathParams) {
1613
+ continue;
1614
+ }
1615
+
1616
+ return {
1617
+ route: item,
1618
+ routers: newRouters,
1619
+ params: pathParams
1620
+ };
1621
+ }
1622
+
1623
+ return null;
1624
+ }
1625
+
1626
+ function buff2str(buffer) {
1627
+ const code = new Uint8Array(buffer);
1628
+ let ret = [];
1629
+ let index = 0;
1630
+
1631
+ while (index < code.length) {
1632
+ let c = code[index++] | 0;
1633
+
1634
+ if (c > 0b11100000) {
1635
+ c = (c & 0xF) << 12;
1636
+ c |= (code[index++] & 0x3F) << 6;
1637
+ c |= code[index++] & 0x3F;
1638
+ } else if (c > 0b11000000) {
1639
+ c = (c & 0x1F) << 12;
1640
+ c |= code[index++] & 0x3F;
1641
+ }
1642
+
1643
+ ret.push(c);
1644
+ }
1645
+
1646
+ return ret.map(x => String.fromCharCode(x)).join('');
1647
+ }
1648
+
1649
+ function mergeArrayBuffer(data, length = data.reduce((a, b) => a + b.byteLength, 0)) {
1650
+ if (data.length === 1) {
1651
+ return data[0];
1652
+ }
1653
+
1654
+ const array = new Uint8Array(length);
1655
+ let offset = 0;
1656
+
1657
+ for (const b of data) {
1658
+ for (let k of new Uint8Array(b)) {
1659
+ array[offset++] = k;
1660
+ }
1661
+ }
1662
+
1663
+ return array.buffer;
1664
+ }
1665
+
1666
+ function getBuffer(encoding, data, size) {
1667
+ if (!size) {
1668
+ const buffer = mergeArrayBuffer(data);
1669
+ return encoding ? buff2str(buffer) : buffer;
1670
+ }
1671
+
1672
+ let length = 0;
1673
+
1674
+ for (let it; it = data.shift();) {
1675
+ if (length + it.byteLength > size) {
1676
+ const buffer = it.slice(0, size - length);
1677
+ length += buffer.byteLength;
1678
+ data.unshift(it.slice(buffer.byteLength));
1679
+ break;
1680
+ }
1681
+ length += it.byteLength;
1682
+
1683
+ if (length === size) {
1684
+ break;
1685
+ }
1686
+ }
1687
+
1688
+ const buffer = mergeArrayBuffer(data, length);
1689
+ return encoding ? buff2str(buffer) : buffer;
1690
+ }
1691
+
1692
+ function str2buff(str) {
1693
+ let out = [];
1694
+
1695
+ for (let c of str.split('').map(ch => ch.charCodeAt(0))) {
1696
+ if (c < 0x80) {
1697
+ out.push(c);
1698
+ } else if (c < 0x800) {
1699
+ out.push(0xC0 | 0x1F & c >> 6);
1700
+ out.push(0x80 | 0x3F & c);
1701
+ } else {
1702
+ out.push(0xE0 | 0x0F & c >> 12);
1703
+ out.push(0x80 | 0x3F & c >> 6);
1704
+ out.push(0x80 | 0x3F & c);
1705
+ }
1706
+ }
1707
+
1708
+ return new Uint8Array(out).buffer;
1709
+ }
1710
+
1711
+ function toBuffer(chunk) {
1712
+ if (typeof chunk === 'string') {
1713
+ return str2buff(chunk);
1714
+ }
1715
+
1716
+ if (ArrayBuffer.isView(chunk)) {
1717
+ return chunk.buffer.slice(chunk.byteOffset, chunk.byteOffset + chunk.byteLength);
1718
+ }
1719
+
1720
+ return chunk;
1721
+ }
1722
+
1723
+ function isBaseWriteType$1(chunk) {
1724
+ if (chunk instanceof ArrayBuffer) {
1725
+ return true;
1726
+ }
1727
+
1728
+ if (ArrayBuffer.isView(chunk)) {
1729
+ return true;
1730
+ }
1731
+
1732
+ try {
1733
+ if (chunk instanceof SharedArrayBuffer) {
1734
+ return true;
1735
+ }
1736
+ } catch {}
1737
+
1738
+ return false;
1739
+ }
1740
+
1741
+ async function* toAsyncIterable(chunk) {
1742
+ if (!chunk) {
1743
+ return;
1744
+ }
1745
+
1746
+ if (typeof chunk === 'string') {
1747
+ return yield chunk;
1748
+ }
1749
+
1750
+ if (typeof chunk !== 'object') {
1751
+ return;
1752
+ }
1753
+
1754
+ if (isBaseWriteType$1(chunk)) {
1755
+ return yield chunk;
1756
+ }
1757
+
1758
+ if (!(Symbol.asyncIterator in chunk || Symbol.iterator in chunk)) {
1759
+ return;
1760
+ }
1761
+
1762
+ for await (const data of chunk) {
1763
+ yield* toAsyncIterable(data);
1764
+ }
1765
+ }
1766
+
1767
+ async function main$1(req, getNext) {
1768
+ const data = [];
1769
+ let length = 0;
1770
+ let [size, encoding, cb] = await getNext();
1771
+
1772
+ for await (const v of toAsyncIterable(req)) {
1773
+ const buffer = toBuffer(v);
1774
+ data.push(buffer);
1775
+ length += buffer.byteLength;
1776
+
1777
+ if (size <= 0) {
1778
+ length = 0;
1779
+ cb(getBuffer(encoding, data));
1780
+ [size, encoding, cb] = await getNext();
1781
+ continue;
1782
+ }
1783
+
1784
+ if (length >= size) {
1785
+ length -= size;
1786
+ cb(getBuffer(encoding, data, size));
1787
+ [size, encoding, cb] = await getNext();
1788
+ }
1789
+
1790
+ while (length && (size <= 0 || size <= length)) {
1791
+ if (size <= 0) {
1792
+ length = 0;
1793
+ cb(getBuffer(encoding, data));
1794
+ [size, encoding, cb] = await getNext();
1795
+ break;
1796
+ }
1797
+
1798
+ length -= size;
1799
+ cb(getBuffer(encoding, data, size));
1800
+ [size, encoding, cb] = await getNext();
1801
+ }
1802
+ }
1803
+
1804
+ if (length) {
1805
+ cb(getBuffer(encoding, data));
1806
+ [size, encoding, cb] = await getNext();
1807
+ }
1808
+
1809
+ cb(null);
1810
+
1811
+ for (;;) {
1812
+ [size, encoding, cb] = await getNext();
1813
+ cb(null);
1814
+ }
1815
+ }
1816
+
1817
+ function createRead(req) {
1818
+ if (!req) {
1819
+ return () => Promise.resolve(null);
1820
+ }
1821
+
1822
+ const list = [];
1823
+ let next = null;
1824
+ main$1(req, function getNext() {
1825
+ return new Promise(r => {
1826
+ const t = list.shift();
1827
+
1828
+ if (t) {
1829
+ return r(t);
1830
+ }
1831
+
1832
+ next = v => {
1833
+ next = null;
1834
+ r(v);
1835
+ };
1836
+ });
1837
+ });
1838
+
1839
+ function read(size = 0, encoding = false) {
1840
+ return new Promise(resolve => {
1841
+ size = Math.max(size, 0);
1842
+
1843
+ if (next) {
1844
+ next([size, encoding, resolve]);
1845
+ return;
1846
+ }
1847
+
1848
+ list.push([size, encoding, resolve]);
1849
+ });
1850
+ }
1851
+
1852
+ return read;
1853
+ }
1854
+
1855
+ const urlRegex = /^(?:(?:https?:)?\/\/(?:(?:[^/?#]*@)?)(?:\d+|(?:\[[0-9a-f:]+\])|(?:\d{1,3}\.){3}\d{1,3}|(?:(?:[a-z0-9\u0100-\uffff]+-*)+\.)+[a-z]+)(?::\d+)?)?((?:\/?[^?#]*)?)((?:\?[^#]*)?)(?:#.*)?$/i;
1856
+
1857
+ function getNameValue(s) {
1858
+ const index = s.indexOf('=');
1859
+
1860
+ if (index < 0) {
1861
+ return [decodeURIComponent(s), ''];
1862
+ }
1863
+
1864
+ return [decodeURIComponent(s.substring(0, index)), decodeURIComponent(s.substring(index + 1))];
1865
+ }
1866
+
1867
+ function parseQuery(s) {
1868
+ const query = {};
1869
+
1870
+ for (const k of s.split('&').filter(Boolean)) {
1871
+ const [index, value] = getNameValue(k);
1872
+
1873
+ if (index in query) {
1874
+ query[index] = [query[index], value].flat();
1875
+ } else {
1876
+ query[index] = [value];
1877
+ }
1878
+ }
1879
+
1880
+ return query;
1881
+ }
1882
+
1883
+ function parseUrl(uri) {
1884
+ const result = urlRegex.exec(uri);
1885
+
1886
+ if (!result) {
1887
+ return ['/', ''];
1888
+ }
1889
+
1890
+ let [, pathname, search] = result;
1891
+ const path = [];
1892
+
1893
+ for (const p of pathname.replace(/^[\\/]+/, '').replace(/[\\/]+/g, '/').split('/')) {
1894
+ if (p === '.') {
1895
+ continue;
1896
+ }
1897
+
1898
+ if (p === '..') {
1899
+ path.pop();
1900
+ continue;
1901
+ }
1902
+
1903
+ path.push(p);
1904
+ }
1905
+
1906
+ return [`/${path.join('/')}`, search];
1907
+ }
1908
+
1909
+ function createRequest(method, path, body, headers = {}) {
1910
+ const [pathname, search] = parseUrl(path);
1911
+ return {
1912
+ method,
1913
+ url: `${pathname}${search}`,
1914
+ headers,
1915
+ pathname,
1916
+ search,
1917
+ query: parseQuery(search.substring(1)),
1918
+ read: typeof body === 'function' ? body : createRead(body)
1919
+ };
1920
+ }
1921
+
1922
+ function createWrite() {
1923
+ let list = [];
1924
+ let ended = false;
1925
+ let endCb = null;
1926
+ let next = null;
1927
+
1928
+ function run() {
1929
+ if (!next) {
1930
+ return;
1931
+ }
1932
+
1933
+ next(list.shift() || null);
1934
+ }
1935
+
1936
+ function write(data) {
1937
+ return new Promise(cb => {
1938
+ if (endCb || ended) {
1939
+ return cb(false);
1940
+ }
1941
+
1942
+ list.push([data, cb]);
1943
+ run();
1944
+ });
1945
+ }
1946
+
1947
+ let endPromise = null;
1948
+
1949
+ function end() {
1950
+ if (!endPromise) {
1951
+ endPromise = new Promise(cb => {
1952
+ if (ended) {
1953
+ return cb();
1954
+ }
1955
+
1956
+ endCb = cb;
1957
+ run();
1958
+ });
1959
+ }
1960
+
1961
+ return endPromise;
1962
+ }
1963
+
1964
+ function getEndFn() {
1965
+ return endCb;
1966
+ }
1967
+
1968
+ function get() {
1969
+ return new Promise(r => {
1970
+ const value = list.shift();
1971
+
1972
+ if (value) {
1973
+ return r(value);
1974
+ }
1975
+
1976
+ if (endCb) {
1977
+ return r(null);
1978
+ }
1979
+
1980
+ next = v => {
1981
+ next = null;
1982
+ r(v);
1983
+ };
1984
+ });
1985
+ }
1986
+
1987
+ const asyncIterable = async function* () {
1988
+ try {
1989
+ for (;;) {
1990
+ const value = await get();
1991
+
1992
+ if (value) {
1993
+ const [data, cb] = value;
1994
+
1995
+ try {
1996
+ yield data;
1997
+ cb(true);
1998
+ } catch {
1999
+ cb(false);
2000
+ }
2001
+
2002
+ continue;
2003
+ }
2004
+
2005
+ if (getEndFn()) {
2006
+ break;
2007
+ }
2008
+ }
2009
+ } finally {
2010
+ ended = true; // eslint-disable-next-line no-cond-assign
2011
+
2012
+ for (let value; value = list.shift();) {
2013
+ const [, cb] = value;
2014
+ cb(false);
2015
+ }
2016
+
2017
+ const endFn = getEndFn();
2018
+
2019
+ if (endFn) {
2020
+ endFn();
2021
+ }
2022
+ }
2023
+ }();
2024
+
2025
+ return [write, end, asyncIterable, () => ended];
2026
+ }
2027
+
2028
+ function isServiceFunc(t) {
2029
+ return typeof Service$1 === 'function';
2030
+ }
2031
+
2032
+ function isServiceConstructor(t) {
2033
+ return Service$1.isPrototypeOf(t);
2034
+ }
2035
+
2036
+ function runService(services, throughData, context, Service, p) {
2037
+ if (!isServiceConstructor(Service)) {
2038
+ if (isServiceFunc()) {
2039
+ return Service(context, ...p);
2040
+ }
2041
+
2042
+ throw new TypeError('the object not is service class or function');
2043
+ }
2044
+
2045
+ let service = services.get(Service);
2046
+
2047
+ if (service) {
2048
+ return service.export(...p);
2049
+ }
2050
+
2051
+ service = new Service(context);
2052
+ services.set(Service, service);
2053
+
2054
+ if (Guard$1.isPrototypeOf(Service)) {
2055
+ relateMap(service, throughData, Service);
2056
+ }
2057
+
2058
+ return service.export(...p);
2059
+ }
2060
+
2061
+ function isBaseWriteType(chunk) {
2062
+ if (chunk instanceof ArrayBuffer) {
2063
+ return true;
2064
+ }
2065
+
2066
+ if (ArrayBuffer.isView(chunk)) {
2067
+ return true;
2068
+ }
2069
+
2070
+ try {
2071
+ if (chunk instanceof SharedArrayBuffer) {
2072
+ return true;
2073
+ }
2074
+ } catch {}
2075
+
2076
+ return false;
2077
+ }
2078
+ /**
2079
+ * 向可写流中写入数据
2080
+ * @param writable 可写流
2081
+ * @param chunk 要写入的数据
2082
+ * @param encoding 如果要写入的数据是字符串,则可用此参数指定编码
2083
+ */
2084
+
2085
+
2086
+ async function writeData(write, isEnd, chunk) {
2087
+ if (!chunk) {
2088
+ return false;
2089
+ }
2090
+
2091
+ if (isEnd()) {
2092
+ return true;
2093
+ }
2094
+
2095
+ if (typeof chunk === 'string') {
2096
+ return write(chunk);
2097
+ }
2098
+
2099
+ if (typeof chunk !== 'object') {
2100
+ return false;
2101
+ }
2102
+
2103
+ if (isBaseWriteType(chunk)) {
2104
+ return write(chunk);
2105
+ }
2106
+
2107
+ if (!(Symbol.asyncIterator in chunk || Symbol.iterator in chunk)) {
2108
+ return false;
2109
+ }
2110
+
2111
+ for await (const data of chunk) {
2112
+ if (isEnd()) {
2113
+ return true;
2114
+ }
2115
+
2116
+ if (!(await writeData(write, isEnd, data))) {
2117
+ return false;
2118
+ }
2119
+ }
2120
+
2121
+ return true;
2122
+ }
2123
+
2124
+ function clearCookie(sentCookies, cookies, name, opt) {
2125
+ let expire = 'Fri, 31 Dec 1999 16:00:00 GMT';
2126
+
2127
+ if (typeof name === 'string') {
2128
+ if (!name) {
2129
+ return;
2130
+ }
2131
+
2132
+ const {
2133
+ domain,
2134
+ path,
2135
+ secure,
2136
+ httpOnly
2137
+ } = opt !== true && opt || {};
2138
+ sentCookies.push({
2139
+ name,
2140
+ value: 'delete',
2141
+ expire,
2142
+ domain,
2143
+ path,
2144
+ secure,
2145
+ httpOnly
2146
+ });
2147
+ } else {
2148
+ const {
2149
+ domain,
2150
+ path,
2151
+ secure,
2152
+ httpOnly
2153
+ } = name || {};
2154
+ sentCookies.length = 0;
2155
+
2156
+ if (opt) {
2157
+ for (let name in cookies) {
2158
+ sentCookies.push({
2159
+ name,
2160
+ value: 'delete',
2161
+ expire,
2162
+ domain,
2163
+ path,
2164
+ secure,
2165
+ httpOnly
2166
+ });
2167
+ }
2168
+ }
2169
+ }
2170
+ }
2171
+
2172
+ function* getCookie(sentCookies, name) {
2173
+ const list = sentCookies;
2174
+
2175
+ for (const item of list) {
2176
+ if (name && item.name !== name) {
2177
+ continue;
2178
+ }
2179
+
2180
+ yield { ...item
2181
+ };
2182
+ }
2183
+ }
2184
+
2185
+ function getRequestCookies(cookie) {
2186
+ let cookies = {};
2187
+
2188
+ for (const item of cookie.replace(/\s/g, '').split(';')) {
2189
+ const v = item.split('=');
2190
+ const name = decodeURIComponent(v.shift());
2191
+ cookies[name] = decodeURIComponent(v.join('='));
2192
+ }
2193
+
2194
+ return cookies;
2195
+ }
2196
+
2197
+ function getCookieHeader(list) {
2198
+ return list.map(({
2199
+ name,
2200
+ value,
2201
+ expire,
2202
+ domain,
2203
+ path,
2204
+ secure,
2205
+ httpOnly
2206
+ }) => name && [`${encodeURI(name)}=${encodeURI(value || '')}`, expire && `Expires=${expire}`, domain && `Domain=${encodeURI(domain)}`, path && `Path=${encodeURI(path)}`, secure && 'Secure', httpOnly && 'HttpOnly'].filter(Boolean).join('; ')).filter(Boolean);
2207
+ }
2208
+
2209
+ const hostRegex = /^(\[[^\]]+\]|^:):(\d+)$/;
2210
+ function createContext(app, params, plugin, throughData, {
2211
+ method,
2212
+ url,
2213
+ pathname,
2214
+ search,
2215
+ query,
2216
+ read,
2217
+ headers: { ...headers
2218
+ }
2219
+ }) {
2220
+ const [write, end, asyncIterable, ended] = createWrite();
2221
+ let headersSent = false;
2222
+ let statusCode = 200;
2223
+ let resHeaders = {};
2224
+ let resolve;
2225
+ let value;
2226
+
2227
+ function send() {
2228
+ if (headersSent) {
2229
+ return;
2230
+ }
2231
+
2232
+ headersSent = true;
2233
+ value = {
2234
+ get statusCode() {
2235
+ return statusCode;
2236
+ },
2237
+
2238
+ get finished() {
2239
+ return ended();
2240
+ },
2241
+
2242
+ headers: Object.freeze({ ...resHeaders
2243
+ }),
2244
+
2245
+ [Symbol.asyncIterator]() {
2246
+ return asyncIterable;
2247
+ }
2248
+
2249
+ };
2250
+
2251
+ if (resolve) {
2252
+ resolve(value);
2253
+ }
2254
+ }
2255
+
2256
+ Object.freeze(headers);
2257
+ const host = headers.host || '';
2258
+ const hostInfo = hostRegex.exec(host);
2259
+ const [hostname, port] = hostInfo ? [hostInfo[1], hostInfo[2]] : [host, ''];
2260
+ const sentCookies = [];
2261
+ const cookies = getRequestCookies(headers['cookie'] || '');
2262
+ const services = new Map();
2263
+ let destroyed = false;
2264
+
2265
+ function isEnd() {
2266
+ return destroyed || ended();
2267
+ }
2268
+
2269
+ let body;
2270
+ let data;
2271
+
2272
+ function setData(d) {
2273
+ data = d;
2274
+ }
2275
+
2276
+ const context = {
2277
+ get body() {
2278
+ return body;
2279
+ },
2280
+
2281
+ set body(b) {
2282
+ body = b;
2283
+ },
2284
+
2285
+ get data() {
2286
+ return data;
2287
+ },
2288
+
2289
+ app,
2290
+ settings: plugin ? app.settings(plugin, true) : app.settings,
2291
+ assets: plugin ? app.assets(plugin, true) : app.assets,
2292
+ logs: plugin ? app.logs(plugin, true) : app.logs,
2293
+ plugin,
2294
+ params,
2295
+ url,
2296
+ method,
2297
+ pathname,
2298
+ search,
2299
+ query,
2300
+ headers,
2301
+ referer: headers.referer || '',
2302
+ host,
2303
+ hostname,
2304
+ port,
2305
+ userAgent: headers['user-agent'] || '',
2306
+ accept: (headers.accept || '').split(/,\s*/).filter(Boolean),
2307
+ acceptLanguage: (headers['accept-language'] || '').split(/,\s*/).filter(Boolean),
2308
+ cookies,
2309
+ read,
2310
+
2311
+ /** 当前对象是否已经被销毁 */
2312
+ get destroyed() {
2313
+ return destroyed;
2314
+ },
2315
+
2316
+ /** 相应是否已结束 */
2317
+ get finished() {
2318
+ return ended();
2319
+ },
2320
+
2321
+ /** 响应头是否已经被发送 */
2322
+ get headersSent() {
2323
+ return headersSent;
2324
+ },
2325
+
2326
+ /** 状态码 */
2327
+ get status() {
2328
+ return statusCode;
2329
+ },
2330
+
2331
+ set status(v) {
2332
+ if (headersSent) {
2333
+ return;
2334
+ }
2335
+
2336
+ statusCode = v;
2337
+ },
2338
+
2339
+ /**
2340
+ * 获取已设置的 cookie 信息
2341
+ */
2342
+ getCookie(name) {
2343
+ return getCookie(sentCookies, name);
2344
+ },
2345
+
2346
+ /**
2347
+ * 设置 cookie
2348
+ * @param name cookie 名称
2349
+ * @param value cookie 内容
2350
+ * @param option 选项
2351
+ */
2352
+ setCookie(name, value, {
2353
+ expire,
2354
+ domain,
2355
+ path,
2356
+ secure,
2357
+ httpOnly
2358
+ } = {}) {
2359
+ if (headersSent) {
2360
+ return;
2361
+ }
2362
+
2363
+ sentCookies.push({
2364
+ name,
2365
+ value,
2366
+ expire,
2367
+ domain,
2368
+ path,
2369
+ secure,
2370
+ httpOnly
2371
+ });
2372
+ resHeaders['set-cookie'] = getCookieHeader(sentCookies);
2373
+ },
2374
+
2375
+ clearCookie(name, opt) {
2376
+ if (headersSent) {
2377
+ return;
2378
+ }
2379
+
2380
+ clearCookie(sentCookies, cookies, name, opt);
2381
+ resHeaders['set-cookie'] = getCookieHeader(sentCookies);
2382
+ },
2383
+
2384
+ service(Service, ...p) {
2385
+ if (destroyed) {
2386
+ throw new Error('This controller is destroyed');
2387
+ }
2388
+
2389
+ return runService(services, throughData, context, Service, p);
2390
+ },
2391
+
2392
+ /** 获取请求头中的 contentType */
2393
+ get requestType() {
2394
+ return headers['content-type'] || '';
2395
+ },
2396
+
2397
+ /** 相应头中的 contentType */
2398
+ get responseType() {
2399
+ return resHeaders['content-type'] || '';
2400
+ },
2401
+
2402
+ set responseType(v) {
2403
+ if (!headersSent) {
2404
+ resHeaders['content-type'] = v;
2405
+ }
2406
+ },
2407
+
2408
+ hasHeader(n) {
2409
+ return n in resHeaders;
2410
+ },
2411
+
2412
+ getHeaderNames() {
2413
+ return Object.keys(resHeaders);
2414
+ },
2415
+
2416
+ getHeaders() {
2417
+ return { ...resHeaders
2418
+ };
2419
+ },
2420
+
2421
+ getHeader(n) {
2422
+ return resHeaders[n];
2423
+ },
2424
+
2425
+ removeHeader(n) {
2426
+ if (!headersSent) {
2427
+ delete resHeaders[n];
2428
+ }
2429
+ },
2430
+
2431
+ setHeader(n, v) {
2432
+ if (headersSent) {
2433
+ return;
2434
+ }
2435
+
2436
+ if (v === undefined) {
2437
+ delete resHeaders[n];
2438
+ } else {
2439
+ resHeaders[n] = v;
2440
+ }
2441
+ },
2442
+
2443
+ async write(chunk) {
2444
+ if (!chunk) {
2445
+ return true;
2446
+ }
2447
+
2448
+ send();
2449
+
2450
+ if (isEnd()) {
2451
+ return true;
2452
+ }
2453
+
2454
+ return writeData(write, isEnd, chunk);
2455
+ },
2456
+
2457
+ exit(status) {
2458
+ if (typeof status === 'number' && status >= 100 && status < 700) {
2459
+ statusCode = status;
2460
+ }
2461
+
2462
+ throw new ExitSignal();
2463
+ },
2464
+
2465
+ transfer(url, is301) {
2466
+ statusCode = is301 ? 301 : 302;
2467
+
2468
+ if (!headersSent) {
2469
+ resHeaders['location'] = url;
2470
+ }
2471
+
2472
+ throw new ExitSignal();
2473
+ },
2474
+
2475
+ request(method, path, {
2476
+ headers,
2477
+ body
2478
+ } = {}) {
2479
+ return app.request(createRequest(method, path, body, headers));
2480
+ }
2481
+
2482
+ };
2483
+
2484
+ async function destroy() {
2485
+ if (destroyed) {
2486
+ return;
2487
+ }
2488
+
2489
+ destroyed = true;
2490
+
2491
+ for (const c of [...services.values()]) {
2492
+ try {
2493
+ await c.destroy();
2494
+ } catch (e) {
2495
+ app.logs.error(e);
2496
+ }
2497
+ }
2498
+
2499
+ send();
2500
+ return end();
2501
+ }
2502
+
2503
+ const response = new Promise(r => {
2504
+ if (headersSent && value) {
2505
+ r(value);
2506
+ } else {
2507
+ resolve = r;
2508
+ }
2509
+ });
2510
+
2511
+ async function runGuards(guards) {
2512
+ for (const Guard of guards) {
2513
+ let guard = services.get(Guard);
2514
+
2515
+ if (!guard) {
2516
+ guard = new Guard(context);
2517
+ relateMap(guard, throughData, Guard);
2518
+ services.set(Guard, guard);
2519
+ }
2520
+
2521
+ if (false === (await guard.decide())) {
2522
+ return false;
2523
+ }
2524
+ }
2525
+
2526
+ return true;
2527
+ }
2528
+
2529
+ return {
2530
+ context,
2531
+ destroy,
2532
+ setData,
2533
+ response,
2534
+ runGuards
2535
+ };
2536
+ }
2537
+
2538
+ function findController(routers, {
2539
+ controller
2540
+ }) {
2541
+ if (Controller$1.isControllerConstructor(controller)) {
2542
+ return controller;
2543
+ }
2544
+
2545
+ for (const {
2546
+ controller
2547
+ } of [...routers].reverse()) {
2548
+ if (Controller$1.isControllerConstructor(controller)) {
2549
+ return controller;
2550
+ }
2551
+ }
2552
+
2553
+ return Controller$1;
2554
+ }
2555
+
2556
+ function* getGuards(routers) {
2557
+ for (const {
2558
+ guards
2559
+ } of [...routers]) {
2560
+ yield* guards;
2561
+ }
2562
+ }
2563
+
2564
+ function returnResult(result, controller, context) {
2565
+ if (context.finished) {
2566
+ return;
2567
+ }
2568
+
2569
+ if (!result) {
2570
+ return;
2571
+ }
2572
+
2573
+ if (context === result) {
2574
+ return;
2575
+ }
2576
+
2577
+ if (controller === result) {
2578
+ return;
2579
+ }
2580
+
2581
+ return controller[returnSymbol](result);
2582
+ }
2583
+
2584
+ async function exec(handle, controller, context, data) {
2585
+ if (typeof handle === 'function') {
2586
+ const result = await handle.call(context, data);
2587
+ return returnResult(result, controller, context);
2588
+ }
2589
+
2590
+ if (typeof handle === 'string') {
2591
+ const fn = controller[handle];
2592
+
2593
+ if (typeof fn !== 'function') {
2594
+ return;
2595
+ }
2596
+
2597
+ const result = await fn.call(controller);
2598
+ return returnResult(result, controller, context);
2599
+ }
2600
+
2601
+ if (handle === optionsSymbol) {
2602
+ const result = await controller[optionsSymbol]();
2603
+ return returnResult(result, controller, context);
2604
+ }
2605
+ }
2606
+
2607
+ async function catchError(app, controller, e) {
2608
+ if (e instanceof ExitSignal) {
2609
+ return;
2610
+ }
2611
+
2612
+ try {
2613
+ await controller[catchSymbol](e);
2614
+ } catch (e) {
2615
+ app.logs.error(e);
2616
+ }
2617
+ }
2618
+
2619
+ async function main(app, route, controller, context, runGuards, routers, destroy, setData) {
2620
+ try {
2621
+ // 初始化
2622
+ await controller[initSymbol]();
2623
+
2624
+ if (!(await runGuards(getGuards(routers)))) {
2625
+ return;
2626
+ }
2627
+
2628
+ const data = await controller[dataSymbol]();
2629
+ setData(data);
2630
+ await exec(route.handle, controller, context, data);
2631
+ } catch (e) {
2632
+ await catchError(app, controller, e);
2633
+ } finally {
2634
+ try {
2635
+ await controller[finallySymbol]();
2636
+ } catch (e) {
2637
+ app.logs.error(e);
2638
+ } // 销毁与回收处理
2639
+
2640
+
2641
+ await destroy();
2642
+ }
2643
+ }
2644
+
2645
+ function run(app, throughData, routers, route, request, params) {
2646
+ const {
2647
+ context,
2648
+ destroy,
2649
+ setData,
2650
+ response,
2651
+ runGuards
2652
+ } = createContext(app, params, route.plugin, throughData, request);
2653
+ const ThisController = findController(routers, route);
2654
+ const controller = new ThisController(context);
2655
+ main(app, route, controller, context, runGuards, routers, destroy, setData);
2656
+ return response;
2657
+ }
2658
+
2659
+ /** 查找请求的处理函数 */
2660
+
2661
+ async function callback(request) {
2662
+ const throughData = new Map();
2663
+ const it = await find(this, request.method, request.pathname, throughData, {}, [], '', 0);
2664
+
2665
+ if (!it) {
2666
+ return null;
2667
+ }
2668
+
2669
+ return run(this, throughData, it.routers, it.route, request, it.params);
2670
+ }
2671
+
2672
+ const dotRegex = /^\.+$/;
2673
+
2674
+ function resolvePath(...paths) {
2675
+ const list = [];
2676
+
2677
+ for (const k of paths.map(p => p.split('/')).flat()) {
2678
+ if (!k || k === '.') {
2679
+ continue;
2680
+ }
2681
+
2682
+ if (dotRegex.test(k)) {
2683
+ list.length = Math.max(0, list.length - k.length + 1);
2684
+ continue;
2685
+ }
2686
+
2687
+ list.push(k);
2688
+ }
2689
+
2690
+ return `${list.join('/')}`;
2691
+ }
2692
+ /** 自扩展接口 */
2693
+
2694
+
2695
+ function subInterface(interfaces, extendsInterfaces, mark, basePath, path, setMark) {
2696
+ if (path === undefined) {
2697
+ return basePath;
2698
+ }
2699
+
2700
+ if (path === '~') {
2701
+ path = mark;
2702
+ } else if (path.substr(0, 2) === '~/') {
2703
+ path = `${mark}/${path.substr(2)}`;
2704
+ } else if (path.substr(0, 2) === '\\~') {
2705
+ path = path.substr(1);
2706
+ }
2707
+
2708
+ return Interface(interfaces, extendsInterfaces, setMark ? resolvePath(path) : mark, setMark ? '' : path, basePath);
2709
+ }
2710
+ /** 自扩展接口 */
2711
+
2712
+
2713
+ function Interface(interfaces, extendsInterfaces, mark = '', path = '', basePath = '') {
2714
+ basePath = resolvePath(basePath, path);
2715
+ const ret = subInterface.bind(null, interfaces, extendsInterfaces, mark, basePath);
2716
+
2717
+ for (const k in interfaces) {
2718
+ const v = interfaces[k];
2719
+ ret[k] = typeof v === 'function' ? (path, ...p) => v(resolvePath(basePath, path), ...p) : v;
2720
+ }
2721
+
2722
+ if (!extendsInterfaces) {
2723
+ return ret;
2724
+ }
2725
+
2726
+ for (const k in extendsInterfaces) {
2727
+ ret[k] = extendsInterfaces[k];
2728
+ }
2729
+
2730
+ return ret;
2731
+ }
2732
+
2733
+ /**
2734
+ * 包装日志文本
2735
+ * @param log 原始的日志
2736
+ * @param opt 包装选项
2737
+ */
2738
+
2739
+ function pack(log, {
2740
+ tags,
2741
+ indent
2742
+ }) {
2743
+ let extendInfo = '';
2744
+
2745
+ if (tags) {
2746
+ if (!Array.isArray(tags)) {
2747
+ tags = [tags];
2748
+ }
2749
+
2750
+ extendInfo = tags.map(tag => `[${tag}]`).join(' ');
2751
+ }
2752
+
2753
+ extendInfo = `${new Date().toISOString()} ${extendInfo}`;
2754
+
2755
+ if (!log.includes('\n')) {
2756
+ return `${extendInfo} ${log}`;
2757
+ }
2758
+
2759
+ if (typeof indent === 'number') {
2760
+ indent = Math.floor(indent);
2761
+
2762
+ if (isFinite(indent) && indent > 0) {
2763
+ indent = Array(indent).fill(' ').join('');
2764
+ }
2765
+ }
2766
+
2767
+ if (!indent || typeof indent !== 'string') {
2768
+ indent = ' ';
2769
+ }
2770
+
2771
+ log = `${extendInfo}\n${log}`;
2772
+ log = log.split('\n').join(`\n${indent}`);
2773
+ return log;
2774
+ }
2775
+
2776
+ function getErrorLog(log) {
2777
+ if (typeof log === 'string') {
2778
+ return log;
2779
+ }
2780
+
2781
+ if (log instanceof Error) {
2782
+ return log.stack || `${log.name}:${log.message}`;
2783
+ }
2784
+
2785
+ return String(log);
2786
+ }
2787
+ const regex1 = /(?:^|\/)(debug|error|warn|info)\/?$/;
2788
+ const regex2 = /^\/?(debug|error|warn|info)(?:\/|$)/;
2789
+
2790
+ function getType(path) {
2791
+ const v1 = regex1.exec(path);
2792
+
2793
+ if (v1) {
2794
+ return v1[1];
2795
+ }
2796
+
2797
+ const v2 = regex2.exec(path);
2798
+
2799
+ if (v2) {
2800
+ return v2[1];
2801
+ }
2802
+
2803
+ return '';
2804
+ }
2805
+
2806
+ async function defaultRead$2() {
2807
+ return '';
2808
+ }
2809
+
2810
+ function defaultWriteInPath(path, log) {
2811
+ console.group(`log @ ${path}`);
2812
+
2813
+ switch (getType(path)) {
2814
+ case 'debug':
2815
+ console.debug(log);
2816
+ break;
2817
+
2818
+ case 'info':
2819
+ console.info(log);
2820
+ break;
2821
+
2822
+ case 'warn':
2823
+ console.warn(log);
2824
+ break;
2825
+
2826
+ case 'error':
2827
+ console.error(log);
2828
+ break;
2829
+
2830
+ default:
2831
+ console.log(log);
2832
+ break;
2833
+ }
2834
+
2835
+ console.groupEnd();
2836
+ }
2837
+
2838
+ async function defaultWrite$2(path, log) {
2839
+ switch (path) {
2840
+ case 'debug':
2841
+ console.debug(log);
2842
+ break;
2843
+
2844
+ case 'info':
2845
+ console.info(log);
2846
+ break;
2847
+
2848
+ case 'warn':
2849
+ console.warn(log);
2850
+ break;
2851
+
2852
+ case 'error':
2853
+ console.error(log);
2854
+ break;
2855
+
2856
+ default:
2857
+ defaultWriteInPath(path, log);
2858
+ break;
2859
+ }
2860
+
2861
+ return true;
2862
+ }
2863
+
2864
+ async function defaultClear() {}
2865
+
2866
+ function initLog({
2867
+ read = defaultRead$2,
2868
+ write = defaultWrite$2,
2869
+ clear = defaultClear
2870
+ } = {}) {
2871
+ function readLog(path) {
2872
+ return read(path);
2873
+ }
2874
+
2875
+ function clearLog(path) {
2876
+ return clear(path);
2877
+ }
2878
+
2879
+ function writeLog(path, log, opt) {
2880
+ if (opt) {
2881
+ log = pack(log, opt);
2882
+ }
2883
+
2884
+ if (log[log.length - 1] !== '\n') {
2885
+ log += '\n';
2886
+ }
2887
+
2888
+ return write(path, log);
2889
+ }
2890
+
2891
+ return Interface({
2892
+ read: readLog,
2893
+ write: writeLog,
2894
+ clear: clearLog
2895
+ }, {
2896
+ async debug(log, opt) {
2897
+ return writeLog('debug', log, opt);
2898
+ },
2899
+
2900
+ async info(log, opt) {
2901
+ return writeLog('info', log, opt);
2902
+ },
2903
+
2904
+ async warn(log, opt) {
2905
+ return writeLog('warn', getErrorLog(log), opt);
2906
+ },
2907
+
2908
+ async error(log, opt) {
2909
+ return writeLog('error', getErrorLog(log), opt);
2910
+ }
2911
+
2912
+ });
2913
+ }
2914
+
2915
+ const idRegexText = '[a-zA-Z][a-zA-Z0-9_-]*';
2916
+ const kRegexText = `${idRegexText}(?:.${idRegexText})*`;
2917
+ const regexText = `^/plugins/((?:@${kRegexText}/)?${kRegexText})/(.+)$`;
2918
+ const regex = new RegExp(regexText);
2919
+ function getPluginPath(path, plugins) {
2920
+ if (!plugins) {
2921
+ return null;
2922
+ }
2923
+
2924
+ const r = regex.exec(path);
2925
+
2926
+ if (!r) {
2927
+ return null;
2928
+ }
2929
+
2930
+ const plugin = plugins[r[1]];
2931
+
2932
+ if (!plugin) {
2933
+ return null;
2934
+ }
2935
+
2936
+ return [plugin, r[2]];
2937
+ }
2938
+
2939
+ async function defaultRead$1() {
2940
+ return undefined;
2941
+ }
2942
+
2943
+ async function defaultWrite$1() {
2944
+ return false;
2945
+ }
2946
+
2947
+ function initSettings({
2948
+ read = defaultRead$1,
2949
+ write = defaultWrite$1
2950
+ } = {}, plugins) {
2951
+ async function readSetting(path) {
2952
+ const ret = await read(path);
2953
+
2954
+ if (ret) {
2955
+ return ret;
2956
+ }
2957
+
2958
+ const p = getPluginPath(path, plugins);
2959
+
2960
+ if (!p) {
2961
+ return null;
2962
+ }
2963
+
2964
+ const [plugin, pluginPath] = p;
2965
+ return plugin.readSettings(pluginPath);
2966
+ }
2967
+
2968
+ function writeSetting(path, cfg) {
2969
+ return write(path, cfg);
2970
+ }
2971
+
2972
+ return Interface({
2973
+ read: readSetting,
2974
+ write: writeSetting
2975
+ }, {});
2976
+ }
2977
+
2978
+ async function defaultRead() {
2979
+ return null;
2980
+ }
2981
+
2982
+ async function defaultWrite() {
2983
+ return false;
2984
+ }
2985
+
2986
+ function initAssets({
2987
+ read = defaultRead,
2988
+ write = defaultWrite,
2989
+ delete: unlink = defaultWrite,
2990
+ stat = defaultRead
2991
+ } = {}, plugins) {
2992
+ async function readAsset(path, encoding) {
2993
+ const ret = await read(path, encoding);
2994
+
2995
+ if (ret !== null) {
2996
+ return ret;
2997
+ }
2998
+
2999
+ const p = getPluginPath(path, plugins);
3000
+
3001
+ if (!p) {
3002
+ return null;
3003
+ }
3004
+
3005
+ const [plugin, pluginPath] = p;
3006
+ return plugin.readAsset(pluginPath, encoding);
3007
+ }
3008
+
3009
+ function writeAsset(path, data) {
3010
+ return write(path, data);
3011
+ }
3012
+
3013
+ function deleteAsset(path) {
3014
+ return unlink(path);
3015
+ }
3016
+
3017
+ async function statAsset(path) {
3018
+ return stat(path);
3019
+ }
3020
+
3021
+ return Interface({
3022
+ read: readAsset,
3023
+ write: writeAsset,
3024
+ delete: deleteAsset,
3025
+ stat: statAsset
3026
+ }, {});
3027
+ }
3028
+
3029
+ class App extends Router {
3030
+ /** 连接的处理函数 */
3031
+
3032
+ /** 设置接口 */
3033
+
3034
+ /** 资产接口 */
3035
+
3036
+ /** 日志接口 */
3037
+ constructor({
3038
+ router,
3039
+ settingApi,
3040
+ assetApi,
3041
+ logApi,
3042
+ path
3043
+ } = {}, plugins = Object.create(null)) {
3044
+ super(path);
3045
+ this.settings = initSettings(settingApi, plugins);
3046
+ this.assets = initAssets(assetApi, plugins);
3047
+ this.logs = initLog(logApi);
3048
+ this.plugins = plugins;
3049
+
3050
+ for (const plugin of Object.values(plugins)) {
3051
+ this.route(plugin.router);
3052
+ }
3053
+
3054
+ if (router instanceof Router) {
3055
+ this.route(router);
3056
+ }
3057
+
3058
+ this.request = callback.bind(this);
3059
+ }
3060
+
3061
+ }
3062
+
3063
+ function set(handle, key, value) {
3064
+ if (value === undefined) {
3065
+ delete handle[key];
3066
+ }
3067
+
3068
+ handle[key] = value;
3069
+ return handle;
3070
+ }
3071
+ /** 设置配置 */
3072
+
3073
+
3074
+ function setTest(test) {
3075
+ return h => set(h, testSymbol, test);
3076
+ }
3077
+ /** 设置方法 */
3078
+
3079
+ function setMethods(...methods) {
3080
+ return h => set(h, methodsSymbol, methods.length ? methods : undefined);
3081
+ }
3082
+ /** 设置选项 */
3083
+
3084
+ function setOptions(options) {
3085
+ return h => set(h, optionsSymbol, options);
3086
+ }
3087
+
3088
+ exports.App = App;
3089
+ exports.Controller = Controller$1;
3090
+ exports.ExitSignal = ExitSignal;
3091
+ exports.Guard = Guard$1;
3092
+ exports.Handle = Handle;
3093
+ exports.Plugin = Plugin;
3094
+ exports.Router = Router;
3095
+ exports.Service = Service$1;
3096
+ exports.catchSymbol = catchSymbol;
3097
+ exports.dataSymbol = dataSymbol;
3098
+ exports.finallySymbol = finallySymbol;
3099
+ exports.initSymbol = initSymbol;
3100
+ exports.methodsSymbol = methodsSymbol;
3101
+ exports.optionsSymbol = optionsSymbol;
3102
+ exports.returnSymbol = returnSymbol;
3103
+ exports.setMethods = setMethods;
3104
+ exports.setOptions = setOptions;
3105
+ exports.setTest = setTest;
3106
+ exports.testSymbol = testSymbol;
3107
+
3108
+ Object.defineProperty(exports, '__esModule', { value: true });
3109
+
3110
+ })));