@miqro/core 1.3.1 → 1.3.5

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 (163) hide show
  1. package/dist/handler/api-handler.d.ts +2 -2
  2. package/dist/handler/api-handler.js +7 -6
  3. package/dist/handler/api-handler.js.map +1 -1
  4. package/dist/handler/api-router-utils.d.ts +1 -8
  5. package/dist/handler/api-router-utils.js +16 -14
  6. package/dist/handler/api-router-utils.js.map +1 -1
  7. package/dist/handler/api-router.d.ts +1 -2
  8. package/dist/handler/api-router.js.map +1 -1
  9. package/dist/handler/app.d.ts +1 -2
  10. package/dist/handler/app.js +95 -13
  11. package/dist/handler/app.js.map +1 -1
  12. package/dist/handler/common/context.d.ts +57 -0
  13. package/dist/handler/common/context.js +123 -0
  14. package/dist/handler/common/context.js.map +1 -0
  15. package/dist/handler/common/index.d.ts +2 -55
  16. package/dist/handler/common/index.js +12 -127
  17. package/dist/handler/common/index.js.map +1 -1
  18. package/dist/handler/common/router-utils.d.ts +51 -0
  19. package/dist/handler/common/router-utils.js +107 -0
  20. package/dist/handler/common/router-utils.js.map +1 -0
  21. package/dist/handler/common/router.d.ts +20 -0
  22. package/dist/handler/common/router.js +82 -0
  23. package/dist/handler/common/router.js.map +1 -0
  24. package/dist/handler/common/tokenize-match.d.ts +18 -9
  25. package/dist/handler/common/tokenize-match.js +35 -28
  26. package/dist/handler/common/tokenize-match.js.map +1 -1
  27. package/dist/handler/feature-router.d.ts +3 -2
  28. package/dist/handler/feature-router.js +3 -3
  29. package/dist/handler/feature-router.js.map +1 -1
  30. package/dist/handler/index.d.ts +1 -4
  31. package/dist/handler/index.js +1 -5
  32. package/dist/handler/index.js.map +1 -1
  33. package/dist/{middleware → handler/middleware}/buffer.d.ts +1 -1
  34. package/dist/{middleware → handler/middleware}/buffer.js +2 -2
  35. package/dist/handler/middleware/buffer.js.map +1 -0
  36. package/dist/{middleware → handler/middleware}/cookie.d.ts +1 -1
  37. package/dist/{middleware → handler/middleware}/cookie.js +1 -1
  38. package/dist/handler/middleware/cookie.js.map +1 -0
  39. package/dist/{middleware → handler/middleware}/cors.d.ts +1 -1
  40. package/dist/{middleware → handler/middleware}/cors.js +2 -2
  41. package/dist/handler/middleware/cors.js.map +1 -0
  42. package/dist/{middleware → handler/middleware}/form.d.ts +1 -1
  43. package/dist/{middleware → handler/middleware}/form.js +2 -2
  44. package/dist/handler/middleware/form.js.map +1 -0
  45. package/dist/handler/middleware/group.d.ts +3 -0
  46. package/dist/{middleware → handler/middleware}/group.js +2 -2
  47. package/dist/handler/middleware/group.js.map +1 -0
  48. package/dist/{middleware → handler/middleware}/index.d.ts +1 -1
  49. package/dist/{middleware → handler/middleware}/index.js +1 -1
  50. package/dist/handler/middleware/index.js.map +1 -0
  51. package/dist/{middleware → handler/middleware}/json.d.ts +1 -1
  52. package/dist/{middleware → handler/middleware}/json.js +2 -2
  53. package/dist/handler/middleware/json.js.map +1 -0
  54. package/dist/{middleware → handler/middleware}/logger.d.ts +1 -1
  55. package/dist/{middleware → handler/middleware}/logger.js +0 -0
  56. package/dist/handler/middleware/logger.js.map +1 -0
  57. package/dist/{middleware → handler/middleware}/parse.d.ts +4 -3
  58. package/dist/{middleware → handler/middleware}/parse.js +11 -1
  59. package/dist/handler/middleware/parse.js.map +1 -0
  60. package/dist/{middleware → handler/middleware}/session.d.ts +2 -2
  61. package/dist/{middleware → handler/middleware}/session.js +3 -3
  62. package/dist/handler/middleware/session.js.map +1 -0
  63. package/dist/{middleware → handler/middleware}/tag.d.ts +1 -1
  64. package/dist/{middleware → handler/middleware}/tag.js +0 -0
  65. package/dist/handler/middleware/tag.js.map +1 -0
  66. package/dist/{middleware → handler/middleware}/text.d.ts +1 -1
  67. package/dist/{middleware → handler/middleware}/text.js +2 -2
  68. package/dist/handler/middleware/text.js.map +1 -0
  69. package/dist/handler/{html.d.ts → response/html.d.ts} +1 -1
  70. package/dist/handler/{html.js → response/html.js} +0 -0
  71. package/dist/handler/response/html.js.map +1 -0
  72. package/dist/handler/response/index.d.ts +3 -0
  73. package/dist/handler/response/index.js +16 -0
  74. package/dist/handler/response/index.js.map +1 -0
  75. package/dist/handler/{response.d.ts → response/json.d.ts} +1 -1
  76. package/dist/handler/{response.js → response/json.js} +1 -1
  77. package/dist/handler/response/json.js.map +1 -0
  78. package/dist/handler/response/result.d.ts +4 -0
  79. package/dist/handler/{result.js → response/result.js} +1 -1
  80. package/dist/handler/response/result.js.map +1 -0
  81. package/dist/index.d.ts +0 -2
  82. package/dist/index.js +0 -2
  83. package/dist/index.js.map +1 -1
  84. package/dist/util/cookie/cookie.d.ts +0 -1
  85. package/dist/util/request/common.d.ts +9 -0
  86. package/dist/util/request/common.js +99 -1
  87. package/dist/util/request/common.js.map +1 -1
  88. package/dist/util/request/index.js +136 -209
  89. package/dist/util/request/index.js.map +1 -1
  90. package/dist/util/session/common.d.ts +16 -0
  91. package/dist/util/session/common.js +49 -0
  92. package/dist/util/session/common.js.map +1 -0
  93. package/dist/util/session/index.d.ts +2 -16
  94. package/dist/util/session/index.js +12 -46
  95. package/dist/util/session/index.js.map +1 -1
  96. package/dist/{service/index.d.ts → util/session/service.d.ts} +3 -3
  97. package/dist/{service/index.js → util/session/service.js} +6 -6
  98. package/dist/util/session/service.js.map +1 -0
  99. package/package.json +1 -2
  100. package/src/handler/api-handler.ts +8 -7
  101. package/src/handler/api-router-utils.ts +17 -20
  102. package/src/handler/api-router.ts +1 -2
  103. package/src/handler/app.ts +95 -10
  104. package/src/handler/common/context.ts +161 -0
  105. package/src/handler/common/index.ts +2 -157
  106. package/src/handler/common/router-utils.ts +140 -0
  107. package/src/handler/common/router.ts +76 -0
  108. package/src/handler/common/tokenize-match.ts +42 -40
  109. package/src/handler/feature-router.ts +4 -3
  110. package/src/handler/index.ts +1 -5
  111. package/src/{middleware → handler/middleware}/buffer.ts +3 -3
  112. package/src/{middleware → handler/middleware}/cookie.ts +2 -2
  113. package/src/{middleware → handler/middleware}/cors.ts +3 -3
  114. package/src/{middleware → handler/middleware}/form.ts +3 -3
  115. package/src/{middleware → handler/middleware}/group.ts +3 -3
  116. package/src/{middleware → handler/middleware}/index.ts +2 -2
  117. package/src/{middleware → handler/middleware}/json.ts +3 -3
  118. package/src/{middleware → handler/middleware}/logger.ts +1 -1
  119. package/src/{middleware → handler/middleware}/parse.ts +14 -4
  120. package/src/{middleware → handler/middleware}/session.ts +5 -5
  121. package/src/{middleware → handler/middleware}/tag.ts +1 -1
  122. package/src/{middleware → handler/middleware}/text.ts +3 -3
  123. package/src/handler/{html.ts → response/html.ts} +1 -1
  124. package/src/handler/response/index.ts +3 -0
  125. package/src/handler/{response.ts → response/json.ts} +1 -1
  126. package/src/handler/{result.ts → response/result.ts} +3 -3
  127. package/src/index.ts +0 -2
  128. package/src/util/request/common.ts +110 -0
  129. package/src/util/request/index.ts +141 -211
  130. package/src/util/session/common.ts +63 -0
  131. package/src/util/session/index.ts +2 -63
  132. package/src/{service/index.ts → util/session/service.ts} +7 -7
  133. package/tsconfig.json +2 -2
  134. package/dist/handler/common/response.d.ts +0 -13
  135. package/dist/handler/common/response.js +0 -55
  136. package/dist/handler/common/response.js.map +0 -1
  137. package/dist/handler/error.d.ts +0 -2
  138. package/dist/handler/error.js +0 -47
  139. package/dist/handler/error.js.map +0 -1
  140. package/dist/handler/html.js.map +0 -1
  141. package/dist/handler/response.js.map +0 -1
  142. package/dist/handler/result.d.ts +0 -4
  143. package/dist/handler/result.js.map +0 -1
  144. package/dist/handler/router.d.ts +0 -28
  145. package/dist/handler/router.js +0 -119
  146. package/dist/handler/router.js.map +0 -1
  147. package/dist/middleware/buffer.js.map +0 -1
  148. package/dist/middleware/cookie.js.map +0 -1
  149. package/dist/middleware/cors.js.map +0 -1
  150. package/dist/middleware/form.js.map +0 -1
  151. package/dist/middleware/group.d.ts +0 -3
  152. package/dist/middleware/group.js.map +0 -1
  153. package/dist/middleware/index.js.map +0 -1
  154. package/dist/middleware/json.js.map +0 -1
  155. package/dist/middleware/logger.js.map +0 -1
  156. package/dist/middleware/parse.js.map +0 -1
  157. package/dist/middleware/session.js.map +0 -1
  158. package/dist/middleware/tag.js.map +0 -1
  159. package/dist/middleware/text.js.map +0 -1
  160. package/dist/service/index.js.map +0 -1
  161. package/src/handler/common/response.ts +0 -59
  162. package/src/handler/error.ts +0 -42
  163. package/src/handler/router.ts +0 -127
@@ -1,158 +1,3 @@
1
- import { getLogger, Logger } from "../../util/logger";
2
- import { Session } from "../../util/session";
3
- import { IncomingHttpHeaders, IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "http";
4
- import { Response } from "./response";
5
- import { normalizePath, parseSearchParams } from "./tokenize-match";
6
- import { URL } from "url";
7
- import { defaultLoggerFormatter } from "../../util/logger/formatter";
8
- import { newURL } from "./helpers";
9
- import { UUID } from "../../util/uuid";
10
- import { COOKIE } from "../../util/cookie";
11
-
12
- export type Method = "get" | "post" | "put" | "delete" | "patch" | "options" | "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS";
13
-
14
- export { BAD_REQUEST, METHOD_NOT_IMPLEMENTED, NOT_FOUND, ERROR_RESPONSE, FORBIDDEN, Response, UNAUTHORIZED } from "./response";
15
-
16
- export type Handler<T = boolean | void | any> = ((ctx: Context) => Promise<T>) | ((ctx: Context) => T);
17
-
18
- export type ErrorHandler<T = boolean | void | any> = ((e: unknown, ctx: Context) => Promise<T>) | ((e: unknown, ctx: Context) => T);
19
-
20
- export class Context {
21
- public readonly url: URL; // new URL(req.url ? req.url : "/", `http://${req.headers.host}`)
22
- public readonly logger: Logger; // new Logger(...)
23
- public readonly startMS: number; // Date.now()
24
- public uuid: string; // a middleware will fill this
25
- public session?: Session; // a middleware will fill this
26
- public results: any[]; // handlers will fill this
27
- public readonly path: string; // normalized path
28
- public readonly hash: string; // from this.url.hash
29
- public readonly method: string; // from this.url.method
30
- public readonly headers: IncomingHttpHeaders; // from this.req.headers
31
- public readonly cookies: { [name: string]: string }; // a middleware will fill this
32
- public query: { [name: string]: string | string[] }; // parseSearchParams will fill this with this.url.searchParams
33
- public params: { [name: string]: string | undefined } = {}; // the router will fill this
34
- public buffer: Buffer; // empty buffer. middleware must read it
35
- public readonly remoteAddress?: string;
36
- public body: any; // a middleware will fill this reading the buffer
37
- constructor(public readonly req: IncomingMessage, public readonly res: ServerResponse, logger?: Logger) {
38
- this.body = undefined as any;
39
- this.res.removeHeader("Date");
40
- this.url = newURL(req.url ? req.url : "/", `http://${req.headers.host}`) as URL;
41
- this.method = req.method ? req.method.toUpperCase() as string : "GET";
42
- this.path = normalizePath(this.url.pathname); // normalized path
43
- this.hash = this.url.hash;
44
- this.query = parseSearchParams(this.url.searchParams);
45
- this.buffer = Buffer.from("");
46
- this.remoteAddress = req.socket.remoteAddress;
47
- this.cookies = {}; // a middleware will fill
48
- this.headers = req.headers;
49
- this.startMS = Date.now();
50
- this.uuid = UUID.v4().toString("utf-8");
51
- this.results = []; // handlers will fill this
52
- const pathToEnv = this.path.replace(/\//ig, "_").toUpperCase();
53
- const identifier = `${pathToEnv === "_" ? "" : pathToEnv.substring(1)}${this.method.toUpperCase()}`;
54
- this.logger = logger ? logger : getLogger(identifier, {
55
- formatter: ({
56
- identifier,
57
- level,
58
- message,
59
- }) => defaultLoggerFormatter({
60
- identifier,
61
- level,
62
- message: `${this.method} ${this.url}${this.uuid ? ` [${this.uuid}]` : ""}${this.remoteAddress ? ` (${this.remoteAddress})` : ""}${this.session ?
63
- ` session[${this.session.username}:${this.session.account}]` :
64
- ""
65
- } ${message}`
66
- })
67
- }, false);
68
- }
69
- public async close(): Promise<void> {
70
- return this.end({
71
- status: 400,
72
- headers: {
73
- connection: "close"
74
- }
75
- });
76
- }
77
- public addVaryHeader(value: number | string | ReadonlyArray<string>): ServerResponse {
78
- const c = this.res.getHeader("Vary");
79
- const current = c ? c instanceof Array ? c.join(", ") : String(c) : "";
80
- const nV = value instanceof Array ? value.join(", ") : String(value);
81
- const newValue = current ? `${current}, ${nV}` : nV;
82
- return this.res.setHeader("Vary", newValue.indexOf("*") !== -1 ? "*" : newValue);
83
- }
84
- public setHeader(name: string, value: number | string | ReadonlyArray<string>): ServerResponse {
85
- return this.res.setHeader(name, value);
86
- }
87
- public setCookie(name: string, value: string, options?: {
88
- encode?: (uriComponent: string | number | boolean) => string;
89
- maxAge?: number | null;
90
- domain?: string;
91
- httpOnly?: boolean;
92
- secure?: boolean;
93
- path?: string;
94
- expires?: Date;
95
- sameSite?: "lax" | "strict" | "none" | true;
96
- }): ServerResponse {
97
- return this.setHeader('Set-Cookie', COOKIE.serialize(name, String(value), options));
98
- }
99
- public async end({ status, headers, body }: Response): Promise<void> {
100
- return new Promise<void>((resolve, reject) => {
101
- try {
102
- this.res.statusCode = status;
103
- const keys = Object.keys(headers);
104
- for (const key of keys) {
105
- if (headers[key] !== undefined) {
106
- this.res.setHeader(key, headers[key] as any);
107
- }
108
- }
109
- this.res.end(body !== undefined ? String(body) : undefined, () => {
110
- resolve();
111
- });
112
- } catch (e) {
113
- reject(e);
114
- }
115
- });
116
- }
117
- /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
118
- public async json(body: any, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
119
- return this.end({
120
- status: status !== undefined ? status : 200,
121
- headers: {
122
- ['Content-Type']: 'application/json; charset=utf-8',
123
- ...headers,
124
- },
125
- body: JSON.stringify(body)
126
- })
127
- }
128
- public async text(text: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
129
- return this.end({
130
- status: status !== undefined ? status : 200,
131
- headers: {
132
- ['Content-Type']: 'plain/text; charset=utf-8',
133
- ...headers
134
- },
135
- body: text
136
- });
137
- }
138
- public async html(html: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
139
- return this.end({
140
- status: status !== undefined ? status : 200,
141
- headers: {
142
- ['Content-Type']: 'text/html; charset=utf-8',
143
- ...headers
144
- },
145
- body: html
146
- })
147
- }
148
- public async redirect(url: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void> {
149
- return this.end({
150
- status: status !== undefined ? status : 302,
151
- headers: {
152
- ['Location']: url,
153
- ...headers
154
- }
155
- })
156
- }
157
- }
158
1
 
2
+ export * from "./router";
3
+ export * from "./context";
@@ -0,0 +1,140 @@
1
+ import { Router } from "./router";
2
+ import { Context, Handler } from "./context";
3
+ import { Method } from "./context";
4
+ import { matchTokenizePath, PathPartToken, tokenizePath } from "./tokenize-match"
5
+ import { ParseRequest } from "../middleware/parse";
6
+ import { Parser, ParseOptions } from "../../util/parser";
7
+ import { SessionHandler, SessionHandlerOptions } from "../middleware/session";
8
+ import { GroupPolicyHandler } from "../middleware/group";
9
+ import { ResultParser } from "../response/result";
10
+ import { ResponseHandler } from "../response/json";
11
+ import { GroupPolicy } from "../../util/session";
12
+
13
+ export interface RouterJSONDoc {
14
+ [path: string]: {
15
+ [method: string]: RouterHandlerOptions
16
+ }
17
+ }
18
+
19
+ export interface RouterHandlerOptions {
20
+ name?: string;
21
+ description?: string;
22
+ parser?: Parser;
23
+ middleware?: Handler | Handler[];
24
+ session?: SessionHandlerOptions | Handler;
25
+ policy?: GroupPolicy;
26
+ request?: {
27
+ headers?: ParseOptions | ParseOptions[];
28
+ query?: ParseOptions | false | ParseOptions[];
29
+ params?: ParseOptions | false | ParseOptions[];
30
+ body?: ParseOptions | false | ParseOptions[];
31
+ };
32
+ response?: true | ParseOptions | ParseOptions[];
33
+ }
34
+
35
+ export class RouterHandler {
36
+
37
+ private readonly tokens: PathPartToken[];
38
+ private readonly handler: Array<Handler | Handler | Router>;
39
+ private readonly isRouter: boolean;
40
+
41
+ public constructor(handler: Array<Handler> | Handler | Router, private readonly path: string | undefined, private readonly method: Method | undefined, private readonly options?: RouterHandlerOptions) {
42
+ this.tokens = tokenizePath(path);
43
+ const routeHandlers = handler instanceof Array ? handler : [handler];
44
+ let handlers: Array<Handler | Router> = []
45
+ this.isRouter = handler instanceof Router;
46
+ if ((!this.isRouter && routeHandlers.length !== routeHandlers.filter(h => typeof h === "function").length) || (this.isRouter && options)) {
47
+ throw new Error("bad arguments");
48
+ }
49
+ if (this.options && this.options.middleware) {
50
+ handlers = handlers.concat(this.options.middleware);
51
+ }
52
+ if (this.options && this.options.session) {
53
+ handlers.push(typeof this.options.session !== "function" ? SessionHandler(this.options.session) : this.options.session);
54
+ }
55
+ if (this.options && this.options.policy) {
56
+ handlers.push(GroupPolicyHandler(this.options.policy));
57
+ }
58
+ if (this.options && this.options.request) {
59
+ handlers.push(ParseRequest(this.options.request));
60
+ }
61
+
62
+ handlers = handlers.concat(routeHandlers);
63
+
64
+ if (this.options && this.options.response) {
65
+ if (typeof this.options.response === "boolean") {
66
+ (handlers as Handler[]).push(ResponseHandler());
67
+ } else {
68
+ (handlers as Handler[]).push(ResultParser(this.options.response, this.options.parser));
69
+ (handlers as Handler[]).push(ResponseHandler());
70
+ }
71
+ }
72
+ this.handler = handlers;
73
+ }
74
+
75
+ public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
76
+ const nPath = this.path && this.path.length > 1 ? this.path.substring(1) : "";
77
+ const nMethod = this.method ? this.method : "";
78
+
79
+ if (this.isRouter) {
80
+ const router: Router = this.handler[0] as Router;
81
+ router.getJSONDoc(doc, nPath);
82
+ } else if(this.options){
83
+ if (!doc[`${prePath}${nPath}`]) {
84
+ doc[`${prePath}${nPath}`] = {};
85
+ }
86
+ if (doc[`${prePath}${nPath}`][nMethod]) {
87
+ throw new Error("cannot create doc routes override each other");
88
+ }
89
+ doc[`${prePath}${nPath}`][nMethod] = this.options;
90
+ }
91
+ return doc;
92
+ }
93
+
94
+ public async invoke(ctx: Context, pathTokens: { value: string; lower: string; }[], prePathTokens: PathPartToken[]): Promise<boolean> {
95
+ for (let i = 0; i < this.handler.length; i++) {
96
+ const h = this.handler[i];
97
+ if (h instanceof Router) {
98
+ if (!this.pushResults(await h.run(ctx, pathTokens, prePathTokens.concat(this.tokens)), ctx)) {
99
+ return false;
100
+ }
101
+ } else {
102
+ if (!this.pushResults(await h(ctx), ctx)) {
103
+ return false;
104
+ }
105
+ }
106
+ }
107
+ return true;
108
+ }
109
+
110
+ public isMatch(
111
+ method: string,
112
+ pathTokens: { value: string; lower: string; }[],
113
+ prePathTokens: PathPartToken[]): {
114
+ match: boolean;
115
+ params?: { [name: string]: string | undefined }
116
+ } {
117
+ if ((this.method === undefined || this.method === method)) {
118
+ if (this.path === undefined) {
119
+ return {
120
+ match: true
121
+ };
122
+ }
123
+ return matchTokenizePath(this.isRouter, prePathTokens.concat(this.tokens), pathTokens);
124
+ }
125
+ return {
126
+ match: false
127
+ };
128
+ }
129
+
130
+ private pushResults(shouldContinue: boolean, ctx: Context): boolean {
131
+ if (shouldContinue === false) {
132
+ // ctx.logger.debug(`avoiding next handlers because handler returned false.`);
133
+ return false;
134
+ } else if (shouldContinue !== true && shouldContinue !== undefined) {
135
+ ctx.logger.trace("pushing to results [%o]", shouldContinue);
136
+ ctx.results.push(shouldContinue);
137
+ }
138
+ return true;
139
+ }
140
+ }
@@ -0,0 +1,76 @@
1
+ import { Method, Handler, Context, ErrorHandler } from "./context";
2
+ import { RouterHandler, RouterJSONDoc, RouterHandlerOptions } from "./router-utils";
3
+ import { normalizePath, PathPartToken, splitPath } from "./tokenize-match";
4
+
5
+ export class Router {
6
+ protected readonly handlers: RouterHandler[] = [];
7
+ protected readonly errorHandlers: ErrorHandler[] = [];
8
+ public get(path: string, handler: Array<Handler> | Handler | Router, options?: RouterHandlerOptions): Router {
9
+ return this.use(handler, path, "get", options);
10
+ }
11
+ public post(path: string, handler: Array<Handler> | Handler | Router, options?: RouterHandlerOptions): Router {
12
+ return this.use(handler, path, "post", options);
13
+ }
14
+ public patch(path: string, handler: Array<Handler> | Handler | Router, options?: RouterHandlerOptions): Router {
15
+ return this.use(handler, path, "patch", options);
16
+ }
17
+ public delete(path: string, handler: Array<Handler> | Handler | Router, options?: RouterHandlerOptions): Router {
18
+ return this.use(handler, path, "delete", options);
19
+ }
20
+ public put(path: string, handler: Array<Handler> | Handler | Router, options?: RouterHandlerOptions): Router {
21
+ return this.use(handler, path, "put", options);
22
+ }
23
+ public options(path: string, handler: Array<Handler> | Handler | Router, options?: RouterHandlerOptions): Router {
24
+ return this.use(handler, path, "options", options);
25
+ }
26
+ public use(handler: Array<Handler> | Handler | Router, path?: string, method?: Method, options?: RouterHandlerOptions): Router {
27
+ const nPath = path !== undefined ? normalizePath(path) : undefined;
28
+ const nMethod = method ? method.toUpperCase() as Method : method;
29
+ this.handlers.push(new RouterHandler(handler, nPath, nMethod, options));
30
+ return this;
31
+ }
32
+ public catch(errorHandler: Array<ErrorHandler> | ErrorHandler): Router {
33
+ const errorHandlers = errorHandler instanceof Array ? errorHandler : [errorHandler];
34
+ for (const e of errorHandlers) {
35
+ this.errorHandlers.push(e);
36
+ }
37
+ return this;
38
+ }
39
+ public async run(ctx: Context, pathTokens?: { value: string; lower: string; }[], prePathTokens: PathPartToken[] = []): Promise<boolean> {
40
+ pathTokens = pathTokens ? pathTokens : splitPath(ctx.path);
41
+ try {
42
+ let shouldContinue = true;
43
+ for (const h of this.handlers) {
44
+ if (!shouldContinue || ctx.res.headersSent) {
45
+ shouldContinue = false;
46
+ break;
47
+ }
48
+ const isMatch = h.isMatch(ctx.method, pathTokens, prePathTokens);
49
+ if (isMatch.match) {
50
+ if (isMatch.params) {
51
+ ctx.params = ctx.params ? {
52
+ ...ctx.params,
53
+ ...isMatch.params
54
+ } : isMatch.params;
55
+ }
56
+ shouldContinue = await h.invoke(ctx, pathTokens, prePathTokens);
57
+ }
58
+ }
59
+ return !ctx.res.headersSent;
60
+ } catch (e: any) {
61
+ for (const eH of this.errorHandlers) {
62
+ const ret = await eH(e, ctx);
63
+ if (ret === false || ctx.res.headersSent) {
64
+ return false;
65
+ }
66
+ }
67
+ throw e; // pass the error along
68
+ }
69
+ }
70
+ public getJSONDoc(doc: RouterJSONDoc = {}, prePath = "/"): RouterJSONDoc {
71
+ for (const h of this.handlers) {
72
+ doc = h.getJSONDoc(doc, prePath);
73
+ }
74
+ return doc;
75
+ }
76
+ }
@@ -8,6 +8,8 @@ export const parseSearchParams = (search: URLSearchParams): { [name: string]: st
8
8
  });
9
9
  return query;
10
10
  };
11
+
12
+ // appends query params to URLSearchParams and returns a copy
11
13
  export const mergeSearchParams = (search: URLSearchParams, append?: { [name: string]: string | string[] | number | boolean | number[] | boolean[] }): URLSearchParams => {
12
14
  const copy = newURLSearchParams(search.toString());
13
15
  if (!append) {
@@ -57,23 +59,37 @@ export const normalizePath = (path: string): string => {
57
59
  }
58
60
  }
59
61
 
60
- export const tokenizePath = (path?: string): {
62
+ export interface PathPartToken {
61
63
  optional: boolean;
62
- wild: boolean;
64
+ wild?: string;
63
65
  token: string;
64
- }[] => {
66
+ lower: string;
67
+ }
68
+
69
+ export const pathPartTokenize = (token: { value: string; lower: string; }): PathPartToken => {
70
+ const isWild = token.value[0] === ":";
71
+ const optional = token.value[token.value.length - 1] === "?";
72
+ const wild = isWild ? token.value.substring(1, token.value.length - (optional ? 1 : 0)) : undefined;
73
+ return {
74
+ optional,
75
+ wild,
76
+ token: token.value,
77
+ lower: token.lower
78
+ }
79
+ }
80
+
81
+ export const splitPath = (path?: string): { value: string; lower: string; }[] => path === undefined ? [] : path.split("/").filter(p => p).map(p => {
82
+ return {
83
+ value: p,
84
+ lower: p.toLocaleLowerCase()
85
+ };
86
+ });
87
+
88
+ export const tokenizePath = (path?: string): PathPartToken[] => {
65
89
  if (path === undefined) {
66
90
  return [];
67
91
  }
68
- const tokens = path.split("/").filter(p => p).map(token => {
69
- const wild = token[0] === ":";
70
- const optional = token[token.length - 1] === "?";
71
- return {
72
- optional,
73
- wild,
74
- token
75
- }
76
- });
92
+ const tokens = splitPath(path).map(token => pathPartTokenize(token));
77
93
  for (let i = 0; i < tokens.length; i++) {
78
94
  if (tokens[i].optional && i != tokens.length - 1) {
79
95
  throw new Error("cannot set a path token as optional that's not the last one");
@@ -82,52 +98,38 @@ export const tokenizePath = (path?: string): {
82
98
  return tokens;
83
99
  }
84
100
 
85
- export const matchTokenizePath = (checkOnlyTokens: boolean, tokens: {
86
- optional: boolean;
87
- wild: boolean;
88
- token: string;
89
- }[], normalizePath: string, prePath?: string): {
101
+ export const matchTokenizePath = (checkAsRouter: boolean, tokens: PathPartToken[], ctxTokens: { value: string; lower: string; }[]): {
90
102
  match: boolean;
91
- params: { [name: string]: string | undefined }
103
+ params?: { [name: string]: string | undefined }
92
104
  } => {
93
- if (prePath !== "/" && prePath !== undefined) {
94
- tokens = (prePath.split("/").filter(p => p).map(s => {
95
- return {
96
- optional: false,
97
- token: s,
98
- wild: false
99
- };
100
- }) as {
101
- optional: boolean;
102
- wild: boolean;
103
- token: string;
104
- }[]).concat(tokens);
105
+ for (let i = 0; i < tokens.length; i++) {
106
+ if (tokens[i].optional && i != tokens.length - 1) {
107
+ throw new Error("cannot set a path token as optional that's not the last one");
108
+ }
105
109
  }
106
-
107
- const ctxTokens = normalizePath.split("/").filter(p => p);
108
110
  const lastTokenIsOptional = tokens.length > 0 ? tokens[tokens.length - 1].optional : false;
109
111
  const couldBeUsingOptional = (lastTokenIsOptional &&
110
112
  (
111
- (!checkOnlyTokens && tokens.length - 1 === ctxTokens.length) ||
112
- (checkOnlyTokens && tokens.length - 1 <= ctxTokens.length)
113
+ (!checkAsRouter && tokens.length - 1 === ctxTokens.length) ||
114
+ (checkAsRouter && tokens.length - 1 <= ctxTokens.length)
113
115
  )
114
116
  );
115
117
 
116
118
  const params: { [name: string]: string | undefined } = {};
117
119
 
118
- if ((!checkOnlyTokens && tokens.length === ctxTokens.length) || couldBeUsingOptional || (checkOnlyTokens && tokens.length <= ctxTokens.length)) {
120
+ if ((!checkAsRouter && tokens.length === ctxTokens.length) || couldBeUsingOptional || (checkAsRouter && tokens.length <= ctxTokens.length)) {
119
121
  // similiar count of tokens
120
122
  for (let i = 0; i < ctxTokens.length; i++) {
121
123
  const ctxToken = ctxTokens[i];
122
- if (checkOnlyTokens && i >= tokens.length) {
124
+ if (checkAsRouter && i >= tokens.length) {
123
125
  break;
124
126
  }
125
127
 
126
- if (tokens[i].wild || ctxToken.toLocaleLowerCase() === tokens[i].token.toLocaleLowerCase()) {
128
+ if (tokens[i].wild || ctxToken.lower === tokens[i].lower) {
127
129
  // check pass
128
- if (tokens[i].wild) {
129
- const paramKey = tokens[i].token.substring(1, tokens[i].token.length - (tokens[i].optional ? 1 : 0));
130
- params[paramKey] = ctxToken;
130
+ const wild = tokens[i].wild;
131
+ if (wild) {
132
+ params[wild] = ctxToken.value;
131
133
  }
132
134
  continue;
133
135
  }
@@ -2,13 +2,14 @@ import { SimpleMap } from "../util/parser/common";
2
2
  import { Logger } from "../util/logger";
3
3
  import { isFeatureEnabled } from "../util/config/featuretoggle";
4
4
  import { normalizePath } from "./common/tokenize-match";
5
- import { Handler, Method } from "./common";
6
- import { Router } from "./router";
5
+ import { Router, Handler, Method } from "./common";
6
+ import { RouterHandlerOptions } from "./common/router-utils";
7
7
 
8
8
  export interface FeatureRouterPathOptions {
9
9
  path: string | string[];
10
10
  method: Method | Method[];
11
11
  handler: Array<Handler> | Handler;
12
+ options?: RouterHandlerOptions;
12
13
  }
13
14
 
14
15
  export type FeatureRouterOptions<T extends FeatureRouterPathOptions = FeatureRouterPathOptions> = SimpleMap<T>;
@@ -64,7 +65,7 @@ export const FeatureRouter = (options: FeatureRouterOptions, logger?: Logger): R
64
65
  throw new Error(`${featureName} collides with feature ${enabledPaths[`${p}${m}`]} on path ${p} method ${m}`)
65
66
  }
66
67
  enabledPaths[`${p}${m}`] = featureName;
67
- router.use(implementation, p, m.toLocaleLowerCase() as Method);
68
+ router.use(implementation, p, m.toLocaleLowerCase() as Method, handlerOptions.options);
68
69
  }
69
70
  }
70
71
  } else {
@@ -1,12 +1,8 @@
1
1
  export * from "./app";
2
- export * from "./router";
3
- //export * from "./error";
4
2
  export * from "./api-handler";
5
3
  export * from "./api-router";
6
4
  export * from "./response";
7
- export * from "./result";
8
5
  export * from "./common";
9
6
  export * from "./feature-router";
10
- export * from "./html";
11
- export * from "../middleware/parse";
12
7
  export * from "./proxy";
8
+ export * from "./middleware";
@@ -1,7 +1,7 @@
1
1
  import { gunzipSync } from "zlib";
2
- import { Context, Handler } from "../handler/common";
3
- import { BadRequestError } from "../util/error";
4
- import { checkEnvVariables } from "../util/config";
2
+ import { Context, Handler } from "../common";
3
+ import { BadRequestError } from "../../util/error";
4
+ import { checkEnvVariables } from "../../util/config";
5
5
 
6
6
  export const DEFAULT_READ_BUFFER_LIMIT = 1024 * 8 * 100;
7
7
 
@@ -1,6 +1,6 @@
1
- import { Handler, Context } from "../handler/common";
1
+ import { Handler, Context } from "../common";
2
2
 
3
- import { COOKIE } from "../util/cookie";
3
+ import { COOKIE } from "../../util/cookie";
4
4
 
5
5
  export const CookieParser = (options?: {
6
6
  decode?(value: string): string;
@@ -1,6 +1,6 @@
1
- import { Context, Handler } from "../handler/common";
2
- import { checkEnvVariables } from "../util/config";
3
- import { BadRequestError } from "../util/error";
1
+ import { Context, Handler } from "../common";
2
+ import { checkEnvVariables } from "../../util/config";
3
+ import { BadRequestError } from "../../util/error";
4
4
 
5
5
  const DEFAULT_CORS_ORIGINS = "*";
6
6
  const DEFAULT_CORS_METHODS = "GET,HEAD,PUT,PATCH,POST,DELETE";
@@ -1,7 +1,7 @@
1
1
  import { parse as queryParse } from "querystring";
2
- import { Context, Handler } from "../handler/common";
3
- import { BadRequestError } from "../util/error";
4
- import { checkEnvVariables } from "../util/config";
2
+ import { Context, Handler } from "../common";
3
+ import { BadRequestError } from "../../util/error";
4
+ import { checkEnvVariables } from "../../util/config";
5
5
  import { DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
6
6
 
7
7
  const DEFAULT_FORM_MAX_KEYS = undefined;
@@ -1,6 +1,6 @@
1
- import { GroupPolicy, policyCheck } from "../util/session";
2
- import { ForbiddenError, UnAuthorizedError } from "../util/error";
3
- import { Context, Handler } from "../handler/common";
1
+ import { GroupPolicy, policyCheck } from "../../util/session";
2
+ import { ForbiddenError, UnAuthorizedError } from "../../util/error";
3
+ import { Context, Handler } from "../common";
4
4
 
5
5
  export const GroupPolicyHandler = (options: GroupPolicy): Handler<void> => {
6
6
  return async (ctx: Context): Promise<void> => {
@@ -1,5 +1,5 @@
1
- import { isFeatureEnabled } from "../util/config";
2
- import { Handler } from "../handler/common";
1
+ import { isFeatureEnabled } from "../../util/config";
2
+ import { Handler } from "../common";
3
3
 
4
4
  import { LoggerHandler } from "./logger";
5
5
  import { TagResponse } from "./tag";
@@ -1,6 +1,6 @@
1
- import { Context, Handler } from "../handler/common";
2
- import { BadRequestError } from "../util/error";
3
- import { checkEnvVariables } from "../util/config";
1
+ import { Context, Handler } from "../common";
2
+ import { BadRequestError } from "../../util/error";
3
+ import { checkEnvVariables } from "../../util/config";
4
4
  import { DEFAULT_READ_BUFFER_LIMIT } from "./buffer";
5
5
 
6
6
  export const JSONParser = (options?: {
@@ -1,4 +1,4 @@
1
- import { Context, Handler } from "../handler/common";
1
+ import { Context, Handler } from "../common";
2
2
 
3
3
  export const LoggerHandler = (options?: {
4
4
  formatter: (ctx: Context) => string;
@@ -1,8 +1,9 @@
1
- import { parse, Parser } from "../util/parser";
2
- import { ParseOptions } from "../util/parser/common";
3
- import { Context, Handler } from "../handler/common";
1
+ import { parse, Parser } from "../../util/parser";
2
+ import { ParseOptions } from "../../util/parser/common";
3
+ import { Context, Handler } from "../common";
4
4
 
5
5
  export interface ParseRequestOptions {
6
+ headers?: ParseOptions | ParseOptions[];
6
7
  query?: ParseOptions | false | ParseOptions[];
7
8
  params?: ParseOptions | false | ParseOptions[];
8
9
  body?: ParseOptions | false | ParseOptions[];
@@ -22,7 +23,7 @@ const ADD_EXTRA: ParseOptions[] = [{
22
23
  const normalizeParseOptions = (option?: ParseOptions | false | ParseOptions[]): ParseOptions[] =>
23
24
  option ? (option instanceof Array ? option : [option]) : (option === false ? NO_OPTIONS : ADD_EXTRA);
24
25
 
25
- const parseRequestPart = (part: "query" | "body" | "params", ctx: Context, option: ParseOptions[], parser?: Parser): void => {
26
+ const parseRequestPart = (part: "query" | "body" | "params" | "headers", ctx: Context, option: ParseOptions[], parser?: Parser): void => {
26
27
  const value = ctx[part] === undefined ? {} : ctx[part];
27
28
  for (let i = 0; i < option.length; i++) {
28
29
  const o = option[i];
@@ -46,9 +47,18 @@ export const ParseRequest = (options: ParseRequestOptions): Handler<void> => {
46
47
  const query = normalizeParseOptions(options.query);
47
48
  const params = normalizeParseOptions(options.params);
48
49
  const body = normalizeParseOptions(options.body);
50
+ const headers = normalizeParseOptions(options.headers);
49
51
 
50
52
  return async (ctx: Context): Promise<void> => {
51
53
  try {
54
+ try {
55
+ if (options.headers !== undefined) {
56
+ parseRequestPart("headers", ctx, headers, options.parser);
57
+ }
58
+ } catch (e) {
59
+ ctx.logger.error("error parsing headers %o", ctx.headers);
60
+ throw e;
61
+ }
52
62
  try {
53
63
  if (options.query !== undefined) {
54
64
  parseRequestPart("query", ctx, query, options.parser);