@midwayjs/core 3.3.6 → 3.4.0-beta.11

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 (43) hide show
  1. package/LICENSE +21 -0
  2. package/dist/baseFramework.d.ts +3 -0
  3. package/dist/baseFramework.js +32 -13
  4. package/dist/common/asyncContextManager.d.ts +61 -0
  5. package/dist/common/asyncContextManager.js +63 -0
  6. package/dist/common/dataSourceManager.d.ts +8 -1
  7. package/dist/common/dataSourceManager.js +61 -3
  8. package/dist/common/fileDetector.d.ts +1 -0
  9. package/dist/common/fileDetector.js +20 -0
  10. package/dist/common/filterManager.d.ts +1 -0
  11. package/dist/common/filterManager.js +37 -5
  12. package/dist/common/serviceFactory.js +2 -1
  13. package/dist/common/webGenerator.d.ts +4 -3
  14. package/dist/common/webGenerator.js +24 -15
  15. package/dist/config/config.default.d.ts +3 -0
  16. package/dist/config/config.default.js +3 -0
  17. package/dist/context/container.js +3 -0
  18. package/dist/error/base.d.ts +1 -1
  19. package/dist/error/base.js +6 -1
  20. package/dist/error/framework.d.ts +8 -0
  21. package/dist/error/framework.js +15 -1
  22. package/dist/error/http.js +16 -16
  23. package/dist/index.d.ts +5 -3
  24. package/dist/index.js +11 -3
  25. package/dist/interface.d.ts +14 -4
  26. package/dist/interface.js +3 -1
  27. package/dist/service/configService.js +7 -4
  28. package/dist/service/middlewareService.js +13 -5
  29. package/dist/service/slsFunctionService.d.ts +25 -0
  30. package/dist/service/slsFunctionService.js +242 -0
  31. package/dist/{common/webRouterCollector.d.ts → service/webRouterService.d.ts} +87 -36
  32. package/dist/{common/webRouterCollector.js → service/webRouterService.js} +121 -116
  33. package/dist/setup.js +3 -0
  34. package/dist/util/contextUtil.d.ts +2 -0
  35. package/dist/util/contextUtil.js +6 -1
  36. package/dist/util/index.d.ts +1 -0
  37. package/dist/util/index.js +23 -2
  38. package/dist/util/pathToRegexp.d.ts +113 -7
  39. package/dist/util/pathToRegexp.js +326 -205
  40. package/package.json +3 -3
  41. package/CHANGELOG.md +0 -2551
  42. package/dist/common/triggerCollector.d.ts +0 -8
  43. package/dist/common/triggerCollector.js +0 -37
@@ -1,39 +1,41 @@
1
1
  "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WebRouterCollector = void 0;
12
+ exports.MidwayWebRouterService = void 0;
4
13
  const decorator_1 = require("@midwayjs/decorator");
5
14
  const util_1 = require("../util");
6
- const container_1 = require("../context/container");
7
- const fileDetector_1 = require("./fileDetector");
8
- const util = require("util");
9
15
  const error_1 = require("../error");
16
+ const util = require("util");
17
+ const pathToRegexp_1 = require("../util/pathToRegexp");
10
18
  const debug = util.debuglog('midway:debug');
11
- class WebRouterCollector {
12
- constructor(baseDir = '', options = {}) {
19
+ let MidwayWebRouterService = class MidwayWebRouterService {
20
+ constructor(options = {}) {
21
+ this.options = options;
13
22
  this.isReady = false;
14
23
  this.routes = new Map();
15
24
  this.routesPriority = [];
16
- this.baseDir = baseDir;
17
- this.options = options;
25
+ this.includeCompileUrlPattern = false;
18
26
  }
19
27
  async analyze() {
20
- if (this.baseDir) {
21
- const container = new container_1.MidwayContainer();
22
- container.setFileDetector(new fileDetector_1.DirectoryFileDetector({
23
- loadDir: this.baseDir,
24
- }));
25
- await container.ready();
26
- }
28
+ this.analyzeController();
29
+ this.sortPrefixAndRouter();
30
+ }
31
+ analyzeController() {
27
32
  const controllerModules = (0, decorator_1.listModule)(decorator_1.CONTROLLER_KEY);
28
33
  for (const module of controllerModules) {
29
- this.collectRoute(module);
30
- }
31
- if (this.options.includeFunctionRouter) {
32
- const fnModules = (0, decorator_1.listModule)(decorator_1.FUNC_KEY);
33
- for (const module of fnModules) {
34
- this.collectFunctionRoute(module);
35
- }
34
+ const controllerOption = (0, decorator_1.getClassMetadata)(decorator_1.CONTROLLER_KEY, module);
35
+ this.addController(module, controllerOption, this.options.includeFunctionRouter);
36
36
  }
37
+ }
38
+ sortPrefixAndRouter() {
37
39
  // filter empty prefix
38
40
  this.routesPriority = this.routesPriority.filter(item => {
39
41
  const prefixList = this.routes.get(item.prefix);
@@ -55,12 +57,17 @@ class WebRouterCollector {
55
57
  return routeB.prefix.length - routeA.prefix.length;
56
58
  });
57
59
  }
58
- collectRoute(module, functionMeta = false) {
60
+ /**
61
+ * dynamically add a controller
62
+ * @param controllerClz
63
+ * @param controllerOption
64
+ * @param functionMeta
65
+ */
66
+ addController(controllerClz, controllerOption, functionMeta = false) {
59
67
  var _a;
60
- const controllerId = (0, decorator_1.getProviderName)(module);
68
+ const controllerId = (0, decorator_1.getProviderName)(controllerClz);
61
69
  debug(`[core]: Found Controller ${controllerId}.`);
62
- const id = (0, decorator_1.getProviderUUId)(module);
63
- const controllerOption = (0, decorator_1.getClassMetadata)(decorator_1.CONTROLLER_KEY, module);
70
+ const id = (0, decorator_1.getProviderUUId)(controllerClz);
64
71
  let priority;
65
72
  // implement middleware in controller
66
73
  const middleware = controllerOption.routerOptions.middleware;
@@ -83,9 +90,18 @@ class WebRouterCollector {
83
90
  middleware,
84
91
  routerOptions: controllerOption.routerOptions,
85
92
  controllerId,
86
- routerModule: module,
93
+ routerModule: controllerClz,
87
94
  });
88
95
  }
96
+ else {
97
+ // 不同的 controller,可能会有相同的 prefix,一旦 options 不同,就要报错
98
+ if (middleware) {
99
+ const originRoute = this.routesPriority.filter(el => {
100
+ return el.prefix === prefix;
101
+ })[0];
102
+ throw new error_1.MidwayDuplicateControllerOptionsError(prefix, controllerId, originRoute.controllerId);
103
+ }
104
+ }
89
105
  // set ignorePrefix
90
106
  if (!this.routes.has(ignorePrefix)) {
91
107
  this.routes.set(ignorePrefix, []);
@@ -95,14 +111,14 @@ class WebRouterCollector {
95
111
  middleware,
96
112
  routerOptions: controllerOption.routerOptions,
97
113
  controllerId,
98
- routerModule: module,
114
+ routerModule: controllerClz,
99
115
  });
100
116
  }
101
- const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.WEB_ROUTER_KEY, module);
117
+ const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.WEB_ROUTER_KEY, controllerClz);
102
118
  if (webRouterInfo && typeof webRouterInfo[Symbol.iterator] === 'function') {
103
119
  for (const webRouter of webRouterInfo) {
104
- const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, module, webRouter.method) || [];
105
- const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, module, webRouter.method) || [];
120
+ const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, controllerClz, webRouter.method) || [];
121
+ const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, controllerClz, webRouter.method) || [];
106
122
  const data = {
107
123
  id,
108
124
  prefix: webRouter.ignoreGlobalPrefix ? ignorePrefix : prefix,
@@ -136,92 +152,29 @@ class WebRouterCollector {
136
152
  }
137
153
  }
138
154
  }
139
- collectFunctionRoute(module, functionMeta = false) {
140
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
141
- // serverlessTrigger metadata
142
- const webRouterInfo = (0, decorator_1.getClassMetadata)(decorator_1.FUNC_KEY, module);
143
- const controllerId = (0, decorator_1.getProviderName)(module);
144
- const id = (0, decorator_1.getProviderUUId)(module);
145
- const prefix = '/';
155
+ /**
156
+ * dynamically add a route to root prefix
157
+ * @param routerPath
158
+ * @param routerFunction
159
+ * @param routerInfoOption
160
+ */
161
+ addRouter(routerFunction, routerInfoOption) {
162
+ const prefix = routerInfoOption.prefix || '';
163
+ routerInfoOption.requestMethod = (routerInfoOption.requestMethod || 'GET').toUpperCase();
146
164
  if (!this.routes.has(prefix)) {
147
165
  this.routes.set(prefix, []);
148
166
  this.routesPriority.push({
149
167
  prefix,
150
- priority: -999,
168
+ priority: 0,
151
169
  middleware: [],
152
170
  routerOptions: {},
153
- controllerId,
154
- routerModule: module,
171
+ controllerId: undefined,
172
+ routerModule: undefined,
155
173
  });
156
174
  }
157
- for (const webRouter of webRouterInfo) {
158
- // 新的 @ServerlessTrigger 写法
159
- if ((_a = webRouter['metadata']) === null || _a === void 0 ? void 0 : _a['path']) {
160
- const routeArgsInfo = (0, decorator_1.getPropertyDataFromClass)(decorator_1.WEB_ROUTER_PARAM_KEY, module, webRouter['methodName']) || [];
161
- const routerResponseData = (0, decorator_1.getPropertyMetadata)(decorator_1.WEB_RESPONSE_KEY, module, webRouter['methodName']) || [];
162
- // 新 http/api gateway 函数
163
- const data = {
164
- id,
165
- prefix,
166
- routerName: '',
167
- url: webRouter['metadata']['path'],
168
- requestMethod: (_c = (_b = webRouter['metadata']) === null || _b === void 0 ? void 0 : _b['method']) !== null && _c !== void 0 ? _c : 'get',
169
- method: webRouter['methodName'],
170
- description: '',
171
- summary: '',
172
- handlerName: `${controllerId}.${webRouter['methodName']}`,
173
- funcHandlerName: `${controllerId}.${webRouter['methodName']}`,
174
- controllerId,
175
- middleware: ((_d = webRouter['metadata']) === null || _d === void 0 ? void 0 : _d['middleware']) || [],
176
- controllerMiddleware: [],
177
- requestMetadata: routeArgsInfo,
178
- responseMetadata: routerResponseData,
179
- };
180
- if (functionMeta) {
181
- const functionMeta = (0, decorator_1.getPropertyMetadata)(decorator_1.SERVERLESS_FUNC_KEY, module, webRouter['methodName']) || {};
182
- const functionName = (_f = (_e = functionMeta['functionName']) !== null && _e !== void 0 ? _e : webRouter['functionName']) !== null && _f !== void 0 ? _f : createFunctionName(module, webRouter['methodName']);
183
- data.functionName = functionName;
184
- data.functionTriggerName = webRouter['type'];
185
- data.functionTriggerMetadata = webRouter['metadata'];
186
- data.functionMetadata = {
187
- functionName,
188
- ...functionMeta,
189
- };
190
- }
191
- this.checkDuplicateAndPush(prefix, data);
192
- }
193
- else {
194
- if (functionMeta) {
195
- const functionMeta = (0, decorator_1.getPropertyMetadata)(decorator_1.SERVERLESS_FUNC_KEY, module, webRouter['methodName']) || {};
196
- const functionName = (_h = (_g = functionMeta['functionName']) !== null && _g !== void 0 ? _g : webRouter['functionName']) !== null && _h !== void 0 ? _h : createFunctionName(module, webRouter['methodName']);
197
- // 其他类型的函数
198
- this.checkDuplicateAndPush(prefix, {
199
- id,
200
- prefix,
201
- routerName: '',
202
- url: '',
203
- requestMethod: '',
204
- method: webRouter['methodName'],
205
- description: '',
206
- summary: '',
207
- handlerName: `${controllerId}.${webRouter['methodName']}`,
208
- funcHandlerName: `${controllerId}.${webRouter['methodName']}`,
209
- controllerId,
210
- middleware: ((_j = webRouter['metadata']) === null || _j === void 0 ? void 0 : _j['middleware']) || [],
211
- controllerMiddleware: [],
212
- requestMetadata: [],
213
- responseMetadata: [],
214
- functionName,
215
- functionTriggerName: webRouter['type'],
216
- functionTriggerMetadata: webRouter['metadata'],
217
- functionMetadata: {
218
- functionName,
219
- ...functionMeta,
220
- },
221
- });
222
- }
223
- }
224
- }
175
+ this.checkDuplicateAndPush(prefix, Object.assign(routerInfoOption, {
176
+ method: routerFunction,
177
+ }));
225
178
  }
226
179
  sortRouter(urlMatchList) {
227
180
  // 1. 绝对路径规则优先级最高如 /ab/cb/e
@@ -299,7 +252,19 @@ class WebRouterCollector {
299
252
  }
300
253
  return this.routes;
301
254
  }
302
- async getFlattenRouterTable() {
255
+ async getFlattenRouterTable(options = {}) {
256
+ if (this.cachedFlattenRouteList && !options.noCache) {
257
+ if (options.compileUrlPattern && !this.includeCompileUrlPattern) {
258
+ this.includeCompileUrlPattern = true;
259
+ // attach match pattern function
260
+ for (const item of this.cachedFlattenRouteList) {
261
+ if (item.fullUrlFlattenString) {
262
+ item.fullUrlCompiledRegexp = pathToRegexp_1.PathToRegexpUtil.toRegexp(item.fullUrlFlattenString);
263
+ }
264
+ }
265
+ }
266
+ return this.cachedFlattenRouteList;
267
+ }
303
268
  if (!this.isReady) {
304
269
  await this.analyze();
305
270
  this.isReady = true;
@@ -308,8 +273,34 @@ class WebRouterCollector {
308
273
  for (const routerPriority of this.routesPriority) {
309
274
  routeArr = routeArr.concat(this.routes.get(routerPriority.prefix));
310
275
  }
276
+ if (options.compileUrlPattern) {
277
+ this.includeCompileUrlPattern = true;
278
+ // attach match pattern function
279
+ for (const item of routeArr) {
280
+ if (item.fullUrlFlattenString) {
281
+ item.fullUrlCompiledRegexp = pathToRegexp_1.PathToRegexpUtil.toRegexp(item.fullUrlFlattenString);
282
+ }
283
+ }
284
+ }
285
+ this.cachedFlattenRouteList = routeArr;
311
286
  return routeArr;
312
287
  }
288
+ async getMatchedRouterInfo(routerUrl, method) {
289
+ const routes = await this.getFlattenRouterTable({
290
+ compileUrlPattern: true,
291
+ });
292
+ let matchedRouterInfo;
293
+ for (const item of routes) {
294
+ if (item.fullUrlCompiledRegexp) {
295
+ if (method.toUpperCase() === item['requestMethod'].toUpperCase() &&
296
+ item.fullUrlCompiledRegexp.test(routerUrl)) {
297
+ matchedRouterInfo = item;
298
+ break;
299
+ }
300
+ }
301
+ }
302
+ return matchedRouterInfo;
303
+ }
313
304
  checkDuplicateAndPush(prefix, routerInfo) {
314
305
  const prefixList = this.routes.get(prefix);
315
306
  const matched = prefixList.filter(item => {
@@ -321,11 +312,25 @@ class WebRouterCollector {
321
312
  if (matched && matched.length) {
322
313
  throw new error_1.MidwayDuplicateRouteError(`${routerInfo.requestMethod} ${routerInfo.url}`, `${matched[0].handlerName}`, `${routerInfo.handlerName}`);
323
314
  }
315
+ // format url
316
+ if (!routerInfo.fullUrlFlattenString &&
317
+ routerInfo.url &&
318
+ typeof routerInfo.url === 'string') {
319
+ routerInfo.fullUrl = (0, util_1.joinURLPath)(prefix, routerInfo.url);
320
+ if (/\*$/.test(routerInfo.fullUrl)) {
321
+ routerInfo.fullUrlFlattenString = routerInfo.fullUrl.replace('*', '(.*)');
322
+ }
323
+ else {
324
+ routerInfo.fullUrlFlattenString = routerInfo.fullUrl;
325
+ }
326
+ }
324
327
  prefixList.push(routerInfo);
325
328
  }
326
- }
327
- exports.WebRouterCollector = WebRouterCollector;
328
- function createFunctionName(target, functionName) {
329
- return (0, decorator_1.getProviderName)(target).replace(/[:#]/g, '-') + '-' + functionName;
330
- }
331
- //# sourceMappingURL=webRouterCollector.js.map
329
+ };
330
+ MidwayWebRouterService = __decorate([
331
+ (0, decorator_1.Provide)(),
332
+ (0, decorator_1.Scope)(decorator_1.ScopeEnum.Singleton),
333
+ __metadata("design:paramtypes", [Object])
334
+ ], MidwayWebRouterService);
335
+ exports.MidwayWebRouterService = MidwayWebRouterService;
336
+ //# sourceMappingURL=webRouterService.js.map
package/dist/setup.js CHANGED
@@ -7,6 +7,7 @@ const decorator_1 = require("@midwayjs/decorator");
7
7
  const util = require("util");
8
8
  const path_1 = require("path");
9
9
  const logger_1 = require("@midwayjs/logger");
10
+ const slsFunctionService_1 = require("./service/slsFunctionService");
10
11
  const debug = util.debuglog('midway:debug');
11
12
  /**
12
13
  * midway framework main entry, this method bootstrap all service and framework.
@@ -95,6 +96,8 @@ function prepareGlobalApplicationContext(globalOptions) {
95
96
  applicationContext.bindClass(_1.MidwayMiddlewareService);
96
97
  applicationContext.bindClass(_1.MidwayLifeCycleService);
97
98
  applicationContext.bindClass(_1.MidwayMockService);
99
+ applicationContext.bindClass(_1.MidwayWebRouterService);
100
+ applicationContext.bindClass(slsFunctionService_1.MidwayServerlessFunctionService);
98
101
  // bind preload module
99
102
  if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
100
103
  for (const preloadModule of globalOptions.preloadModules) {
@@ -1,5 +1,7 @@
1
1
  import { IConfigurationOptions, IMidwayContainer, IMidwayFramework } from '../interface';
2
+ import { AsyncContextManager } from '../common/asyncContextManager';
2
3
  export declare const getCurrentApplicationContext: () => IMidwayContainer;
3
4
  export declare const getCurrentMainFramework: <APP extends import("../interface").IMidwayBaseApplication<CTX>, CTX extends import("../interface").Context, CONFIG extends IConfigurationOptions>() => IMidwayFramework<APP, CTX, CONFIG, unknown, unknown>;
4
5
  export declare const getCurrentMainApp: <APP extends import("../interface").IMidwayBaseApplication<import("../interface").Context>>() => APP;
6
+ export declare const getCurrentAsyncContextManager: () => AsyncContextManager;
5
7
  //# sourceMappingURL=contextUtil.d.ts.map
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getCurrentMainApp = exports.getCurrentMainFramework = exports.getCurrentApplicationContext = void 0;
3
+ exports.getCurrentAsyncContextManager = exports.getCurrentMainApp = exports.getCurrentMainFramework = exports.getCurrentApplicationContext = void 0;
4
+ const interface_1 = require("../interface");
4
5
  const getCurrentApplicationContext = () => {
5
6
  return global['MIDWAY_APPLICATION_CONTEXT'];
6
7
  };
@@ -17,4 +18,8 @@ const getCurrentMainApp = () => {
17
18
  return undefined;
18
19
  };
19
20
  exports.getCurrentMainApp = getCurrentMainApp;
21
+ const getCurrentAsyncContextManager = () => {
22
+ return (0, exports.getCurrentApplicationContext)().get(interface_1.ASYNC_CONTEXT_MANAGER_KEY);
23
+ };
24
+ exports.getCurrentAsyncContextManager = getCurrentAsyncContextManager;
20
25
  //# sourceMappingURL=contextUtil.js.map
@@ -90,4 +90,5 @@ export declare function pathMatching(options: any): (ctx?: any) => any;
90
90
  */
91
91
  export declare function wrapMiddleware(mw: FunctionMiddleware<any, any>, options: any): (context: any, next: any, options?: any) => any;
92
92
  export declare function isIncludeProperty(obj: any, prop: string): boolean;
93
+ export declare function wrapAsync(handler: any): (...args: any[]) => any;
93
94
  //# sourceMappingURL=index.d.ts.map
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isIncludeProperty = exports.wrapMiddleware = exports.pathMatching = exports.toPathMatch = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.getCurrentDateString = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetPrototypeMethod = exports.joinURLPath = exports.getUserHome = exports.parsePrefix = exports.safelyGet = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
3
+ exports.wrapAsync = exports.isIncludeProperty = exports.wrapMiddleware = exports.pathMatching = exports.toPathMatch = exports.transformRequestObjectByType = exports.deprecatedOutput = exports.getCurrentDateString = exports.delegateTargetProperties = exports.delegateTargetMethod = exports.delegateTargetAllPrototypeMethod = exports.delegateTargetPrototypeMethod = exports.joinURLPath = exports.getUserHome = exports.parsePrefix = exports.safelyGet = exports.safeRequire = exports.getCurrentEnvironment = exports.isDevelopmentEnvironment = void 0;
4
4
  const path_1 = require("path");
5
5
  const fs_1 = require("fs");
6
6
  const util_1 = require("util");
@@ -238,7 +238,7 @@ function toPathMatch(pattern) {
238
238
  return ctx => pattern;
239
239
  }
240
240
  if (typeof pattern === 'string') {
241
- const reg = (0, pathToRegexp_1.pathToRegexp)(pattern, [], { end: false });
241
+ const reg = pathToRegexp_1.PathToRegexpUtil.toRegexp(pattern.replace('*', '(.*)'));
242
242
  if (reg.global)
243
243
  reg.lastIndex = 0;
244
244
  return ctx => reg.test(ctx.path);
@@ -313,4 +313,25 @@ function isIncludeProperty(obj, prop) {
313
313
  return false;
314
314
  }
315
315
  exports.isIncludeProperty = isIncludeProperty;
316
+ function wrapAsync(handler) {
317
+ return (...args) => {
318
+ if (typeof args[args.length - 1] === 'function') {
319
+ const callback = args.pop();
320
+ if (handler.constructor.name !== 'AsyncFunction') {
321
+ const err = new TypeError('Must be an AsyncFunction');
322
+ return callback(err);
323
+ }
324
+ // 其他事件场景
325
+ return handler.apply(handler, args).then(result => {
326
+ callback(null, result);
327
+ }, err => {
328
+ callback(err);
329
+ });
330
+ }
331
+ else {
332
+ return handler.apply(handler, args);
333
+ }
334
+ };
335
+ }
336
+ exports.wrapAsync = wrapAsync;
316
337
  //# sourceMappingURL=index.js.map
@@ -1,17 +1,123 @@
1
+ interface ParseOptions {
2
+ /**
3
+ * Set the default delimiter for repeat parameters. (default: `'/'`)
4
+ */
5
+ delimiter?: string;
6
+ /**
7
+ * List of characters to automatically consider prefixes when parsing.
8
+ */
9
+ prefixes?: string;
10
+ }
1
11
  /**
2
- * this file fork from path-to-regexp package v1.8.0
12
+ * Parse a string for the raw tokens.
3
13
  */
14
+ declare function parse(str: string, options?: ParseOptions): Token[];
15
+ interface TokensToFunctionOptions {
16
+ /**
17
+ * When `true` the regexp will be case sensitive. (default: `false`)
18
+ */
19
+ sensitive?: boolean;
20
+ /**
21
+ * Function for encoding input strings for output.
22
+ */
23
+ encode?: (value: string, token: Key) => string;
24
+ /**
25
+ * When `false` the function can produce an invalid (unmatched) path. (default: `true`)
26
+ */
27
+ validate?: boolean;
28
+ }
29
+ /**
30
+ * Compile a string to a template function for the path.
31
+ */
32
+ declare function compile<P extends object = object>(str: string, options?: ParseOptions & TokensToFunctionOptions): PathFunction<P>;
33
+ declare type PathFunction<P extends object = object> = (data?: P) => string;
34
+ interface RegexpToFunctionOptions {
35
+ /**
36
+ * Function for decoding strings for params.
37
+ */
38
+ decode?: (value: string, token: Key) => string;
39
+ }
40
+ /**
41
+ * A match result contains data about the path match.
42
+ */
43
+ interface MatchResult<P extends object = object> {
44
+ path: string;
45
+ index: number;
46
+ params: P;
47
+ }
48
+ /**
49
+ * A match is either `false` (no match) or a match result.
50
+ */
51
+ declare type Match<P extends object = object> = false | MatchResult<P>;
52
+ /**
53
+ * The match function takes a string and returns whether it matched the path.
54
+ */
55
+ declare type MatchFunction<P extends object = object> = (path: string) => Match<P>;
56
+ /**
57
+ * Create path match function from `path-to-regexp` spec.
58
+ */
59
+ declare function match<P extends object = object>(str: Path, options?: ParseOptions & TokensToRegexpOptions & RegexpToFunctionOptions): MatchFunction<P>;
60
+ /**
61
+ * Metadata about a key.
62
+ */
63
+ interface Key {
64
+ name: string | number;
65
+ prefix: string;
66
+ suffix: string;
67
+ pattern: string;
68
+ modifier: string;
69
+ }
70
+ /**
71
+ * A token is a string (nothing special) or key metadata (capture group).
72
+ */
73
+ declare type Token = string | Key;
74
+ interface TokensToRegexpOptions {
75
+ /**
76
+ * When `true` the regexp will be case sensitive. (default: `false`)
77
+ */
78
+ sensitive?: boolean;
79
+ /**
80
+ * When `true` the regexp won't allow an optional trailing delimiter to match. (default: `false`)
81
+ */
82
+ strict?: boolean;
83
+ /**
84
+ * When `true` the regexp will match to the end of the string. (default: `true`)
85
+ */
86
+ end?: boolean;
87
+ /**
88
+ * When `true` the regexp will match from the beginning of the string. (default: `true`)
89
+ */
90
+ start?: boolean;
91
+ /**
92
+ * Sets the final character for non-ending optimistic matches. (default: `/`)
93
+ */
94
+ delimiter?: string;
95
+ /**
96
+ * List of characters that can also be "end" characters.
97
+ */
98
+ endsWith?: string;
99
+ /**
100
+ * Encode path tokens for use in the `RegExp`.
101
+ */
102
+ encode?: (value: string) => string;
103
+ }
104
+ /**
105
+ * Supported `path-to-regexp` input types.
106
+ */
107
+ declare type Path = string | RegExp | Array<string | RegExp>;
4
108
  /**
5
109
  * Normalize the given path string, returning a regular expression.
6
110
  *
7
111
  * An empty array can be passed in for the keys, which will hold the
8
112
  * placeholder key descriptions. For example, using `/user/:id`, `keys` will
9
113
  * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
10
- *
11
- * @param {(string|RegExp|Array)} path
12
- * @param {(Array|Object)=} keys
13
- * @param {Object=} options
14
- * @return {!RegExp}
15
114
  */
16
- export declare function pathToRegexp(path: any, keys: any, options: any): any;
115
+ declare function toRegexp(path: Path, keys?: Key[], options?: TokensToRegexpOptions & ParseOptions): RegExp;
116
+ export declare const PathToRegexpUtil: {
117
+ toRegexp: typeof toRegexp;
118
+ compile: typeof compile;
119
+ parse: typeof parse;
120
+ match: typeof match;
121
+ };
122
+ export {};
17
123
  //# sourceMappingURL=pathToRegexp.d.ts.map