@miqro/core 4.0.1 → 5.0.2

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 (220) hide show
  1. package/build/app.d.ts +15 -11
  2. package/build/app.js +22 -20
  3. package/build/app.js.map +1 -1
  4. package/build/common.d.ts +106 -0
  5. package/build/common.js +477 -0
  6. package/build/common.js.map +1 -0
  7. package/build/lib.d.ts +7 -38
  8. package/build/lib.js +6 -33
  9. package/build/lib.js.map +1 -1
  10. package/build/middleware/body-parser.d.ts +78 -0
  11. package/build/middleware/body-parser.js +552 -0
  12. package/build/middleware/body-parser.js.map +1 -0
  13. package/build/middleware/router.d.ts +114 -0
  14. package/build/middleware/router.js +704 -0
  15. package/build/middleware/router.js.map +1 -0
  16. package/build/middleware/session.d.ts +27 -3
  17. package/build/middleware/session.js +238 -18
  18. package/build/middleware/session.js.map +1 -1
  19. package/build/types.d.ts +309 -0
  20. package/build/types.js +455 -0
  21. package/build/types.js.map +1 -0
  22. package/build/{websocket/cluster.d.ts → websocket.d.ts} +13 -2
  23. package/build/websocket.js +316 -0
  24. package/build/websocket.js.map +1 -0
  25. package/package.json +7 -7
  26. package/src/app.ts +36 -32
  27. package/src/common.ts +528 -0
  28. package/src/lib.ts +63 -101
  29. package/src/middleware/body-parser.ts +597 -0
  30. package/src/middleware/router.ts +840 -0
  31. package/src/middleware/session.ts +249 -19
  32. package/src/types.ts +785 -0
  33. package/src/websocket.ts +356 -0
  34. package/build/api-router.d.ts +0 -34
  35. package/build/api-router.js +0 -48
  36. package/build/api-router.js.map +0 -1
  37. package/build/app-utils.d.ts +0 -13
  38. package/build/app-utils.js +0 -78
  39. package/build/app-utils.js.map +0 -1
  40. package/build/common/api-router-types.d.ts +0 -28
  41. package/build/common/api-router-types.js +0 -24
  42. package/build/common/api-router-types.js.map +0 -1
  43. package/build/common/api-router-utils.d.ts +0 -3
  44. package/build/common/api-router-utils.js +0 -118
  45. package/build/common/api-router-utils.js.map +0 -1
  46. package/build/common/config/config.d.ts +0 -15
  47. package/build/common/config/config.js +0 -38
  48. package/build/common/config/config.js.map +0 -1
  49. package/build/common/config/featuretoggle.d.ts +0 -1
  50. package/build/common/config/featuretoggle.js +0 -6
  51. package/build/common/config/featuretoggle.js.map +0 -1
  52. package/build/common/config/loader.d.ts +0 -13
  53. package/build/common/config/loader.js +0 -64
  54. package/build/common/config/loader.js.map +0 -1
  55. package/build/common/context.d.ts +0 -57
  56. package/build/common/context.js +0 -137
  57. package/build/common/context.js.map +0 -1
  58. package/build/common/error/badrequesterror.d.ts +0 -3
  59. package/build/common/error/badrequesterror.js +0 -7
  60. package/build/common/error/badrequesterror.js.map +0 -1
  61. package/build/common/error/configfilenotfound.d.ts +0 -3
  62. package/build/common/error/configfilenotfound.js +0 -7
  63. package/build/common/error/configfilenotfound.js.map +0 -1
  64. package/build/common/error/forbiddenerror.d.ts +0 -3
  65. package/build/common/error/forbiddenerror.js +0 -7
  66. package/build/common/error/forbiddenerror.js.map +0 -1
  67. package/build/common/error/notfound.d.ts +0 -3
  68. package/build/common/error/notfound.js +0 -7
  69. package/build/common/error/notfound.js.map +0 -1
  70. package/build/common/error/notimplemented.d.ts +0 -3
  71. package/build/common/error/notimplemented.js +0 -7
  72. package/build/common/error/notimplemented.js.map +0 -1
  73. package/build/common/error/unauthorizederror.d.ts +0 -3
  74. package/build/common/error/unauthorizederror.js +0 -7
  75. package/build/common/error/unauthorizederror.js.map +0 -1
  76. package/build/common/logger/constants.d.ts +0 -14
  77. package/build/common/logger/constants.js +0 -22
  78. package/build/common/logger/constants.js.map +0 -1
  79. package/build/common/logger/factory.d.ts +0 -16
  80. package/build/common/logger/factory.js +0 -47
  81. package/build/common/logger/factory.js.map +0 -1
  82. package/build/common/logger/interfaces.d.ts +0 -18
  83. package/build/common/logger/interfaces.js +0 -2
  84. package/build/common/logger/interfaces.js.map +0 -1
  85. package/build/common/logger/logger.d.ts +0 -35
  86. package/build/common/logger/logger.js +0 -95
  87. package/build/common/logger/logger.js.map +0 -1
  88. package/build/common/logger/transport/console.d.ts +0 -5
  89. package/build/common/logger/transport/console.js +0 -37
  90. package/build/common/logger/transport/console.js.map +0 -1
  91. package/build/common/logger/transport/file.d.ts +0 -2
  92. package/build/common/logger/transport/file.js +0 -25
  93. package/build/common/logger/transport/file.js.map +0 -1
  94. package/build/common/parser.d.ts +0 -7
  95. package/build/common/parser.js +0 -44
  96. package/build/common/parser.js.map +0 -1
  97. package/build/common/router-default-logger-factory.d.ts +0 -4
  98. package/build/common/router-default-logger-factory.js +0 -38
  99. package/build/common/router-default-logger-factory.js.map +0 -1
  100. package/build/common/router-handler.d.ts +0 -20
  101. package/build/common/router-handler.js +0 -154
  102. package/build/common/router-handler.js.map +0 -1
  103. package/build/common/router-types.d.ts +0 -63
  104. package/build/common/router-types.js +0 -86
  105. package/build/common/router-types.js.map +0 -1
  106. package/build/common/router-utils.d.ts +0 -3
  107. package/build/common/router-utils.js +0 -46
  108. package/build/common/router-utils.js.map +0 -1
  109. package/build/common/session/common.d.ts +0 -37
  110. package/build/common/session/common.js +0 -2
  111. package/build/common/session/common.js.map +0 -1
  112. package/build/common/session/service.d.ts +0 -26
  113. package/build/common/session/service.js +0 -154
  114. package/build/common/session/service.js.map +0 -1
  115. package/build/common/tokenize-match.d.ts +0 -19
  116. package/build/common/tokenize-match.js +0 -73
  117. package/build/common/tokenize-match.js.map +0 -1
  118. package/build/common/url-utils.d.ts +0 -6
  119. package/build/common/url-utils.js +0 -48
  120. package/build/common/url-utils.js.map +0 -1
  121. package/build/middleware/buffer.d.ts +0 -6
  122. package/build/middleware/buffer.js +0 -78
  123. package/build/middleware/buffer.js.map +0 -1
  124. package/build/middleware/cookie.d.ts +0 -4
  125. package/build/middleware/cookie.js +0 -15
  126. package/build/middleware/cookie.js.map +0 -1
  127. package/build/middleware/cors.d.ts +0 -8
  128. package/build/middleware/cors.js +0 -89
  129. package/build/middleware/cors.js.map +0 -1
  130. package/build/middleware/form.d.ts +0 -6
  131. package/build/middleware/form.js +0 -58
  132. package/build/middleware/form.js.map +0 -1
  133. package/build/middleware/group.d.ts +0 -3
  134. package/build/middleware/group.js +0 -77
  135. package/build/middleware/group.js.map +0 -1
  136. package/build/middleware/json.d.ts +0 -6
  137. package/build/middleware/json.js +0 -55
  138. package/build/middleware/json.js.map +0 -1
  139. package/build/middleware/logger.d.ts +0 -4
  140. package/build/middleware/logger.js +0 -16
  141. package/build/middleware/logger.js.map +0 -1
  142. package/build/middleware/parse.d.ts +0 -14
  143. package/build/middleware/parse.js +0 -88
  144. package/build/middleware/parse.js.map +0 -1
  145. package/build/middleware/result.d.ts +0 -9
  146. package/build/middleware/result.js +0 -62
  147. package/build/middleware/result.js.map +0 -1
  148. package/build/middleware/tag.d.ts +0 -4
  149. package/build/middleware/tag.js +0 -10
  150. package/build/middleware/tag.js.map +0 -1
  151. package/build/middleware/text.d.ts +0 -5
  152. package/build/middleware/text.js +0 -46
  153. package/build/middleware/text.js.map +0 -1
  154. package/build/proxy.d.ts +0 -19
  155. package/build/proxy.js +0 -74
  156. package/build/proxy.js.map +0 -1
  157. package/build/router.d.ts +0 -26
  158. package/build/router.js +0 -116
  159. package/build/router.js.map +0 -1
  160. package/build/static.d.ts +0 -14
  161. package/build/static.js +0 -211
  162. package/build/static.js.map +0 -1
  163. package/build/websocket/cluster.js +0 -114
  164. package/build/websocket/cluster.js.map +0 -1
  165. package/build/websocket/server.d.ts +0 -15
  166. package/build/websocket/server.js +0 -127
  167. package/build/websocket/server.js.map +0 -1
  168. package/build/websocket/types.d.ts +0 -39
  169. package/build/websocket/types.js +0 -2
  170. package/build/websocket/types.js.map +0 -1
  171. package/build/websocket/utils.d.ts +0 -8
  172. package/build/websocket/utils.js +0 -77
  173. package/build/websocket/utils.js.map +0 -1
  174. package/src/api-router.ts +0 -50
  175. package/src/app-utils.ts +0 -82
  176. package/src/common/api-router-types.ts +0 -52
  177. package/src/common/api-router-utils.ts +0 -126
  178. package/src/common/config/config.ts +0 -49
  179. package/src/common/config/featuretoggle.ts +0 -6
  180. package/src/common/config/loader.ts +0 -81
  181. package/src/common/context.ts +0 -192
  182. package/src/common/error/badrequesterror.ts +0 -6
  183. package/src/common/error/configfilenotfound.ts +0 -6
  184. package/src/common/error/forbiddenerror.ts +0 -6
  185. package/src/common/error/notfound.ts +0 -6
  186. package/src/common/error/notimplemented.ts +0 -6
  187. package/src/common/error/unauthorizederror.ts +0 -6
  188. package/src/common/logger/constants.ts +0 -28
  189. package/src/common/logger/factory.ts +0 -53
  190. package/src/common/logger/interfaces.ts +0 -19
  191. package/src/common/logger/logger.ts +0 -136
  192. package/src/common/logger/transport/console.ts +0 -36
  193. package/src/common/logger/transport/file.ts +0 -26
  194. package/src/common/parser.ts +0 -50
  195. package/src/common/router-default-logger-factory.ts +0 -44
  196. package/src/common/router-handler.ts +0 -186
  197. package/src/common/router-types.ts +0 -153
  198. package/src/common/router-utils.ts +0 -47
  199. package/src/common/session/common.ts +0 -40
  200. package/src/common/session/service.ts +0 -175
  201. package/src/common/tokenize-match.ts +0 -98
  202. package/src/common/url-utils.ts +0 -46
  203. package/src/middleware/buffer.ts +0 -82
  204. package/src/middleware/cookie.ts +0 -20
  205. package/src/middleware/cors.ts +0 -98
  206. package/src/middleware/form.ts +0 -61
  207. package/src/middleware/group.ts +0 -74
  208. package/src/middleware/json.ts +0 -57
  209. package/src/middleware/logger.ts +0 -18
  210. package/src/middleware/parse.ts +0 -105
  211. package/src/middleware/result.ts +0 -73
  212. package/src/middleware/tag.ts +0 -15
  213. package/src/middleware/text.ts +0 -47
  214. package/src/proxy.ts +0 -99
  215. package/src/router.ts +0 -140
  216. package/src/static.ts +0 -242
  217. package/src/websocket/cluster.ts +0 -128
  218. package/src/websocket/server.ts +0 -135
  219. package/src/websocket/types.ts +0 -41
  220. package/src/websocket/utils.ts +0 -95
package/src/types.ts ADDED
@@ -0,0 +1,785 @@
1
+ import { ParserInterface, Schema } from "@miqro/parser";
2
+ import { CookieSerializeOptions, parse, serialize } from "cookie";
3
+ import { randomUUID } from "crypto";
4
+ import { IncomingMessage, OutgoingHttpHeaders, ServerResponse } from "http";
5
+ import { Socket } from "net";
6
+ import { Duplex } from "stream";
7
+
8
+ /**
9
+ * Types
10
+ */
11
+
12
+ export interface LoggerErrorEventInit {
13
+ bubbles?: boolean;
14
+ cancelable?: boolean;
15
+ composed?: boolean;
16
+ error: any;
17
+ }
18
+
19
+ export class LoggerErrorEvent extends Event {
20
+ public error: any;
21
+
22
+ constructor(event: string, init: LoggerErrorEventInit) {
23
+ super(event, init);
24
+ this.error = init.error;
25
+ }
26
+ }
27
+
28
+ export type LogLevel = "error" | "warn" | "info" | "debug" | "trace" | "none";
29
+
30
+ export interface WriteArgs {
31
+ level: LogLevel;
32
+ message?: any;
33
+ optionalParams: any[]
34
+ }
35
+
36
+ export interface LoggerTransportWriteArgs extends WriteArgs {
37
+ out: string;
38
+ }
39
+
40
+ export interface LoggerTransport {
41
+ level?: LogLevel;
42
+
43
+ write(args: LoggerTransportWriteArgs): Promise<void> | void;
44
+ }
45
+
46
+ export type LoggerFormatter = (args: { identifier: string, level: LogLevel, message: string }) => string;
47
+
48
+ export interface MinimalLogger {
49
+ log(message?: any, ...optionalParams: any[]): void;
50
+
51
+ info(message?: any, ...optionalParams: any[]): void;
52
+
53
+ trace(message?: any, ...optionalParams: any[]): void;
54
+
55
+ debug(message?: any, ...optionalParams: any[]): void;
56
+
57
+ warn(message?: any, ...optionalParams: any[]): void;
58
+
59
+ error(message?: any, ...optionalParams: any[]): void;
60
+ }
61
+
62
+ export type ConfigOutput = { [name: string]: string };
63
+
64
+ export interface LoadConfigOut {
65
+ combined: ConfigOutput;
66
+ outputs: ConfigOutput[]
67
+ }
68
+
69
+ export interface LoggerFactoryArgs { identifier: string, level: LogLevel; options?: { transports?: LoggerTransport[]; formatter?: LoggerFormatter; } }
70
+
71
+ export type LoggerFactory = (args: LoggerFactoryArgs) => MinimalLogger;
72
+
73
+ export const GroupPolicySchema: Schema<GroupPolicy> = {
74
+ type: "object",
75
+ properties: {
76
+ groups: {
77
+ type: "array",
78
+ arrayType: "string|string[]"
79
+ },
80
+ groupPolicy: {
81
+ type: "enum",
82
+ enumValues: ["at_least_one", "all"]
83
+ }
84
+ }
85
+ }
86
+
87
+ export interface SessionHandlerOptions {
88
+ authService: {
89
+ verify(args: { token: string; req: Request; }): Promise<Session | null>;
90
+ };
91
+ options?: {
92
+ tokenLocation: "header" | "query" | "cookie";
93
+ tokenLocationName: string | ((req: Request) => Promise<string>);
94
+ setCookieOptions?: {
95
+ httpOnly: boolean;
96
+ secure: boolean;
97
+ path: string | ((req: Request) => Promise<string>);
98
+ sameSite: "lax" | "strict" | "none";
99
+ }
100
+ }
101
+ }
102
+
103
+ export const SessionHandlerOptionsSchema: Schema<SessionHandlerOptions> = {
104
+ type: "object",
105
+ properties: {
106
+ tokenLocation: {
107
+ type: "enum",
108
+ enumValues: ["header", "query", "cookie"]
109
+ },
110
+ tokenLocationName: "string|function",
111
+ setCookieOptions: {
112
+ type: "object?",
113
+ properties: {
114
+ httpOnly: "boolean",
115
+ secure: "boolean",
116
+ path: "string|function",
117
+ sameSite: {
118
+ type: "enum",
119
+ enumValues: ["lax", "strict", "none"]
120
+ }
121
+ }
122
+ }
123
+ }
124
+ };
125
+
126
+ type Dict<T = any> = {
127
+ [key: string]: T
128
+ }
129
+
130
+ export interface NoTokenSession extends Dict {
131
+ account: string;
132
+ username: string;
133
+ groups: string[];
134
+ }
135
+
136
+ export interface Session extends NoTokenSession {
137
+ token: string;
138
+ }
139
+
140
+ export type GroupPolicyType = "at_least_one" | "all";
141
+
142
+ export type GroupPolicyGroups = string | string[];
143
+
144
+ export interface GroupPolicy {
145
+ groups: GroupPolicyGroups[];
146
+ groupPolicy: GroupPolicyType;
147
+ }
148
+
149
+ export type Method =
150
+ "get"
151
+ | "post"
152
+ | "put"
153
+ | "delete"
154
+ | "patch"
155
+ | "options"
156
+ | "GET"
157
+ | "POST"
158
+ | "PUT"
159
+ | "DELETE"
160
+ | "PATCH"
161
+ | "OPTIONS";
162
+
163
+ //export const IGNORE_HEADER = ["keep-alive", "connection"];
164
+
165
+ export interface HandlerResponse {
166
+ status?: number;
167
+ headers?: OutgoingHttpHeaders;
168
+ body?: any;
169
+ }
170
+
171
+ export type Handler<T = boolean | void | HandlerResponse> = ((req: Request, res: Response) => Promise<T>) | ((req: Request, res: Response) => T);
172
+
173
+ export type ErrorHandler<T = boolean | void | any> =
174
+ ((e: unknown, req: Request, res: Response) => Promise<T>)
175
+ | ((e: unknown, req: Request, res: Response) => T);
176
+
177
+
178
+ export type SchemaProperties = { [key: string]: Schema | string; };
179
+ const OptionalSchema: Schema<SchemaProperties> = {
180
+ type: "string?|dict[]!?",
181
+ dictType: "Schema|string"
182
+ }
183
+ const OptionalSchemaWithBoolean: Schema<SchemaProperties> = {
184
+ type: "boolean?|string?|dict[]!?",
185
+ dictType: "Schema|string"
186
+ }
187
+ export type ParserMode = "remove_extra" | "add_extra" | "no_extra";
188
+ const OptionalParserModeSchema: Schema<ParserMode> = {
189
+ type: "enum?",
190
+ enumValues: ["remove_extra", "add_extra", "no_extra"]
191
+ }
192
+
193
+ export const RouteOptionsSchema: Schema<RouteOptions> = {
194
+ type: "object",
195
+ properties: {
196
+ name: "string?",
197
+ description: "string?",
198
+ identifier: "string?",
199
+ apiName: "string?",
200
+ policy: {
201
+ type: "object?",
202
+ properties: GroupPolicySchema.properties
203
+ },
204
+ response: {
205
+ type: "object?|boolean?",
206
+ properties: {
207
+ status: "number[]!?",
208
+ headers: OptionalSchema,
209
+ headersMode: OptionalParserModeSchema,
210
+ body: OptionalSchemaWithBoolean,
211
+ bodyMode: OptionalParserModeSchema,
212
+ middleware: "function[]!?"
213
+ }
214
+ },
215
+ request: {
216
+ type: "object?",
217
+ properties: {
218
+ headers: OptionalSchema,
219
+ headersMode: OptionalParserModeSchema,
220
+ query: OptionalSchemaWithBoolean,
221
+ queryMode: OptionalParserModeSchema,
222
+ params: OptionalSchemaWithBoolean,
223
+ paramsMode: OptionalParserModeSchema,
224
+ body: OptionalSchemaWithBoolean,
225
+ bodyMode: OptionalParserModeSchema
226
+ }
227
+ }
228
+ }
229
+ };
230
+
231
+ export interface RouteOptions {
232
+ name?: string;
233
+ identifier?: string;
234
+ apiName?: string;
235
+ description?: string;
236
+ policy?: GroupPolicy;
237
+ request?: {
238
+ headers?: string | SchemaProperties[] | SchemaProperties;
239
+ headersMode?: ParserMode;
240
+ query?: boolean | string | SchemaProperties[] | SchemaProperties;
241
+ queryMode?: ParserMode;
242
+ params?: string | SchemaProperties | boolean | SchemaProperties[];
243
+ paramsMode?: ParserMode;
244
+ body?: string | SchemaProperties | boolean | SchemaProperties[];
245
+ bodyMode?: ParserMode;
246
+ };
247
+ response?: {
248
+ status?: number | number[];
249
+ headers?: string | SchemaProperties | SchemaProperties[];
250
+ headersMode?: ParserMode;
251
+ body?: boolean | string | SchemaProperties | SchemaProperties[];
252
+ bodyMode?: ParserMode;
253
+ middleware?: Handler | Handler[];
254
+ } | boolean;
255
+ }
256
+
257
+ export interface RouteJSONDoc extends RouteOptions {
258
+ identifier: string;
259
+ }
260
+
261
+ export interface RouterJSONDoc {
262
+ [path: string]: {
263
+ [method: string]: RouteJSONDoc
264
+ }
265
+ }
266
+
267
+ export const RouterHandlerOptionsSchema: Schema<RouterHandlerOptions> = {
268
+ type: "object",
269
+ properties: {
270
+ ...RouteOptionsSchema.properties,
271
+ parser: {
272
+ type: "object?",
273
+ properties: {
274
+ parse: "function"
275
+ },
276
+ mode: "add_extra"
277
+ },
278
+ middleware: "function[]!?",
279
+ session: {
280
+ type: "object?|function?",
281
+ properties: SessionHandlerOptionsSchema.properties
282
+ }
283
+ }
284
+ };
285
+
286
+ export interface RouterHandlerOptions extends RouteOptions {
287
+ parser?: ParserInterface;
288
+ middleware?: Handler | Handler[];
289
+ session?: SessionHandlerOptions | Handler;
290
+ }
291
+
292
+ export const HandlerWithOptionsSchema: Schema<HandlerWithOptions> = {
293
+ type: "object",
294
+ properties: {
295
+ ...RouterHandlerOptionsSchema.properties,
296
+ handler: "function[]!"
297
+ }
298
+ };
299
+
300
+ export interface HandlerWithOptions extends RouterHandlerOptions {
301
+ handler: Handler | Array<Handler>;
302
+ }
303
+
304
+ export interface RouterOptions {
305
+ loggerFactory?: (uuid: string, req: Request) => MinimalLogger;
306
+ }
307
+
308
+ export interface MinimalRouter {
309
+ run: (req: Request, res: Response, pathTokens?: PathPart[], prePathTokens?: PathPartToken[]) => Promise<boolean>;
310
+ getJSONDoc: (doc?: RouterJSONDoc, prePath?: string) => RouterJSONDoc;
311
+ }
312
+
313
+ export const MinimalRouterSchema: Schema<MinimalRouter> = {
314
+ type: "object",
315
+ properties: {
316
+ run: "function",
317
+ getJSONDoc: "function"
318
+ },
319
+ mode: "add_extra"
320
+ }
321
+
322
+ export function isMinimalRouter(obj: any) {
323
+ return typeof obj === "object" && typeof obj.run === "function" && typeof obj.getJSONDoc === "function";
324
+ }
325
+
326
+ /**
327
+ * # APIRoute
328
+ *
329
+ * src/api/comment/get.js
330
+ * ```typescript
331
+ *import { APIRouter } from "@miqro/core";
332
+ *const route: APIRoute = {
333
+ * ...
334
+ *};
335
+ *export default route;
336
+ * ```
337
+ */
338
+ export interface APIRoute extends RouterHandlerOptions {
339
+ postFolder?: boolean,
340
+ method?: Method | "use" | "USE";
341
+ path?: string;
342
+ handler: Handler | Array<Handler> | MinimalRouter;
343
+ }
344
+
345
+ export interface APIRouterOptions {
346
+ dirname: string;
347
+ apiName?: string;
348
+ path?: string;
349
+ }
350
+
351
+ export const APIRouterOptionsSchema: Schema<APIRouterOptions> = {
352
+ type: "object",
353
+ properties: {
354
+ dirname: "string",
355
+ apiName: "string?",
356
+ path: "string?"
357
+ }
358
+ };
359
+
360
+ export const APIRouteSchema: Schema<APIRoute> = {
361
+ type: "object",
362
+ properties: {
363
+ ...RouterHandlerOptionsSchema.properties,
364
+ postFolder: "boolean?",
365
+ method: "string?",
366
+ path: "string?",
367
+ handler: {
368
+ type: "function[]!|object",
369
+ properties: MinimalRouterSchema.properties,
370
+ mode: MinimalRouterSchema.mode
371
+ }
372
+ }
373
+ };
374
+
375
+ export interface Request extends IncomingMessage {
376
+ startMS: number;
377
+ logger: MinimalLogger;
378
+ session?: Session;
379
+ uuid: string;
380
+ path: string; // normalized path
381
+ hash: string; // from this.url.hash
382
+ cookies: { [name: string]: string };
383
+ params: { [name: string]: string | undefined }; // the router will fill this
384
+ buffer?: Buffer; // empty buffer. middleware must read it
385
+ query: { [name: string]: string | string[] };
386
+ results: any[]; // handlers will fill this
387
+ body?: any; // a middleware will fill this reading the buffer
388
+ }
389
+
390
+ export class Request extends IncomingMessage implements Request {
391
+ startMS: number;
392
+ body?: any; // a middleware will fill this reading the buffer
393
+ logger: MinimalLogger;
394
+ uuid: string;
395
+ path: string; // normalized path
396
+ hash: string; // from url.hash
397
+ searchParams: URLSearchParams;// from url.searchParams
398
+ cookies: { [name: string]: string };
399
+ params: { [name: string]: string | undefined }; // the router will fill this
400
+ buffer?: Buffer; // empty buffer. middleware must read it
401
+ query: { [name: string]: string | string[] };
402
+ results: any[]; // handlers will fill this
403
+ constructor(socket: Socket) {
404
+ super(socket);
405
+ this.logger = console;
406
+ this.path = null as any;
407
+ this.hash = null as any;
408
+ this.searchParams = null as any;
409
+ this.query = null as any;
410
+
411
+ this.cookies = Object.create(null);
412
+ this.params = Object.create(null);
413
+ this.results = [];
414
+ this.startMS = Date.now();
415
+ this.uuid = randomUUID();
416
+ let vURL: string | undefined;
417
+ Object.defineProperty(this, "url", {
418
+ get: () => {
419
+ return vURL;
420
+ },
421
+ set: (v) => {
422
+ vURL = v;
423
+ const url = newURL(vURL ? vURL : "/") as URL;
424
+ this.searchParams = url.searchParams;
425
+ this.path = normalizePath(url.pathname); // normalized path
426
+ this.hash = url.hash;
427
+ this.query = parseSearchParams(this.searchParams);
428
+ }
429
+ });
430
+ let vCookie: string | undefined;
431
+ Object.defineProperty(this.headers, "cookie", {
432
+ get: () => {
433
+ return vCookie;
434
+ },
435
+ set: (v) => {
436
+ vCookie = v;
437
+ this.cookies = Object.create(null);
438
+ const cookies = parse(vCookie || '');
439
+ const cookieList = Object.keys(cookies);
440
+ for (const name of cookieList) {
441
+ const value = cookies[name];
442
+ if (value) {
443
+ this.cookies[name] = value;
444
+ }
445
+ }
446
+ }
447
+ });
448
+ let vMethod: string | undefined;
449
+ Object.defineProperty(this, "method", {
450
+ get: () => {
451
+ return vMethod;
452
+ },
453
+ set: (v?: string | undefined) => {
454
+ vMethod = v ? v.toLowerCase() : v;
455
+ }
456
+ });
457
+ }
458
+ }
459
+
460
+ export interface Response<Request extends IncomingMessage = IncomingMessage> extends ServerResponse<Request> {
461
+ //logger: Logger;
462
+ asyncClose(): Promise<void>;
463
+ asyncEnd(args?: {
464
+ body?: any;
465
+ status?: number;
466
+ headers?: OutgoingHttpHeaders;
467
+ }): Promise<void>;
468
+ asyncWrite(chunk: any): Promise<void>;
469
+ json(body: any, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
470
+ addVaryHeader(value: number | string | ReadonlyArray<string>): ServerResponse;
471
+ setCookie(name: string, value: string, options?: CookieSerializeOptions): ServerResponse;
472
+ html(html: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
473
+ text(text: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
474
+ redirect(url: string, headers?: OutgoingHttpHeaders, status?: number): Promise<void>;
475
+ }
476
+
477
+ export class Response<Request extends IncomingMessage = IncomingMessage> extends ServerResponse<Request> implements Response<Request> {
478
+ public static IGNORE_HEADER = ["keep-alive", "connection"];
479
+ //logger: Logger;
480
+ constructor(req: Request) {
481
+ super(req);
482
+ //this.logger = null as any;
483
+ this.removeHeader("Date");
484
+ }
485
+ async redirect(url: string, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
486
+ return this.asyncEnd({
487
+ status: status !== undefined ? status : 302,
488
+ headers: {
489
+ ['Location']: url,
490
+ ...headers
491
+ }
492
+ })
493
+ }
494
+ async html(html: string, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
495
+ return this.asyncEnd({
496
+ status: status !== undefined ? status : 200,
497
+ headers: {
498
+ ['Content-Type']: 'text/html; charset=utf-8',
499
+ ...headers
500
+ },
501
+ body: html
502
+ })
503
+ }
504
+ async text(text: string, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
505
+ return this.asyncEnd({
506
+ status: status !== undefined ? status : 200,
507
+ headers: {
508
+ ['Content-Type']: 'plain/text; charset=utf-8',
509
+ ...headers
510
+ },
511
+ body: text
512
+ });
513
+ }
514
+ public setCookie(name: string, value: string, options?: CookieSerializeOptions): ServerResponse {
515
+ return this.setHeader('Set-Cookie', serialize(name, String(value), options));
516
+ }
517
+ addVaryHeader(value: number | string | ReadonlyArray<string>): ServerResponse {
518
+ const c = this.getHeader("Vary");
519
+ const current = c ? c instanceof Array ? c.join(", ") : String(c) : "";
520
+ const nV = value instanceof Array ? value.join(", ") : String(value);
521
+ const newValue = current ? `${current}, ${nV}` : nV;
522
+ return this.setHeader("Vary", newValue.indexOf("*") !== -1 ? "*" : newValue);
523
+ }
524
+ async asyncClose(): Promise<void> {
525
+ return this.asyncEnd({
526
+ status: 400,
527
+ headers: {
528
+ connection: "close"
529
+ }
530
+ });
531
+ }
532
+ async json(body: any, headers?: OutgoingHttpHeaders, status?: unknown): Promise<void> {
533
+ return this.asyncEnd({
534
+ status: status !== undefined ? status : 200,
535
+ headers: {
536
+ ['Content-Type']: 'application/json; charset=utf-8',
537
+ ...headers,
538
+ },
539
+ body: JSON.stringify(body)
540
+ })
541
+ }
542
+ public async asyncWrite(chunk: any): Promise<void> {
543
+ return new Promise((resolve, reject) => {
544
+ this.write(chunk, function (error?: Error | null) {
545
+ if (error) {
546
+ reject(error);
547
+ } else {
548
+ resolve();
549
+ }
550
+ });
551
+ });
552
+ }
553
+ public async asyncEnd(args?: {
554
+ body?: unknown;
555
+ status?: unknown;
556
+ headers?: OutgoingHttpHeaders;
557
+ }): Promise<void> {
558
+ if (this.headersSent) {
559
+ return Promise.reject(new Error("already ended"));
560
+ }
561
+ return new Promise<void>((resolve, reject) => {
562
+ try {
563
+ if (this.headersSent) {
564
+ reject(new Error("already ended"));
565
+ } else {
566
+ const body = args ? args.body : undefined;
567
+ if (args !== undefined) {
568
+ const { status, headers } = args;
569
+ const nStatus = status !== undefined ? parseInt(String(status), 10) : 200;
570
+ if (isNaN(nStatus)) {
571
+ reject(new Error("status not a number!"));
572
+ } else {
573
+ //console.log("nStatus = [%s][%s]", nStatus, typeof nStatus);
574
+ this.statusCode = nStatus;
575
+ if (headers) {
576
+ const keys = Object.keys(headers);
577
+ for (const key of keys) {
578
+ if (Response.IGNORE_HEADER.indexOf(key.toLocaleLowerCase()) !== -1) {
579
+ //this.logger.warn("ignoring " + key);
580
+ continue;
581
+ }
582
+ if (headers[key] !== undefined) {
583
+ this.setHeader(key, headers[key] as any);
584
+ }
585
+ }
586
+ }
587
+ }
588
+ }
589
+ this.setHeader("connection", "close");
590
+ const nBody = body !== undefined ? (body instanceof Buffer ? body : String(body)) : null;
591
+ //console.log("body = [%s][%s]", nBody, typeof nBody);
592
+ this.end(nBody, () => {
593
+ resolve();
594
+ });
595
+ }
596
+ } catch (e) {
597
+ reject(e);
598
+ }
599
+ });
600
+ }
601
+ }
602
+
603
+ export interface PathParams {
604
+ [name: string]: string | undefined
605
+ }
606
+
607
+ export interface PathPartToken extends PathPart {
608
+ optional: boolean;
609
+ wild?: string;
610
+ }
611
+
612
+ export interface PathPart {
613
+ value: string;
614
+ lower: string;
615
+ }
616
+
617
+ function pathPartTokenize(token: PathPart): PathPartToken {
618
+ const isWild = token.value[0] === ":";
619
+ const optional = token.value[token.value.length - 1] === "?";
620
+ const wild = isWild ? token.value.substring(1, token.value.length - (optional ? 1 : 0)) : undefined;
621
+ return {
622
+ optional,
623
+ wild,
624
+ value: token.value,
625
+ lower: token.lower
626
+ }
627
+ }
628
+
629
+ export const splitPath = (path?: string): PathPart[] => path === undefined ? [] : path.split("/").filter(p => p).map(p => {
630
+ return {
631
+ value: p,
632
+ lower: p.toLocaleLowerCase()
633
+ };
634
+ });
635
+
636
+ export function tokenizePath(path?: string): PathPartToken[] {
637
+ if (path === undefined) {
638
+ return [];
639
+ }
640
+ const tokens = splitPath(path).map(token => pathPartTokenize(token));
641
+ for (let i = 0; i < tokens.length; i++) {
642
+ if (tokens[i].optional && i != tokens.length - 1) {
643
+ throw new Error("cannot set a path token as optional that's not the last one");
644
+ }
645
+ }
646
+ return tokens;
647
+ }
648
+
649
+ export function matchTokenizePath(checkAsRouter: boolean, pathTokens: PathPartToken[], requestParts: PathPart[]): {
650
+ match: boolean;
651
+ params?: { [name: string]: string | undefined }
652
+ } {
653
+ for (let i = 0; i < pathTokens.length; i++) {
654
+ if (pathTokens[i].optional && i != pathTokens.length - 1) {
655
+ throw new Error("cannot set a path token as optional that's not the last one");
656
+ }
657
+ }
658
+ const lastTokenIsOptional = pathTokens.length > 0 ? pathTokens[pathTokens.length - 1].optional : false;
659
+ const couldBeUsingOptional = (lastTokenIsOptional &&
660
+ (
661
+ (!checkAsRouter && pathTokens.length - 1 === requestParts.length) ||
662
+ (checkAsRouter && pathTokens.length - 1 <= requestParts.length)
663
+ )
664
+ );
665
+
666
+ const params: { [name: string]: string | undefined } = Object.create(null);
667
+
668
+ if ((!checkAsRouter && pathTokens.length === requestParts.length) || couldBeUsingOptional || (checkAsRouter && pathTokens.length <= requestParts.length)) {
669
+ // similar count of tokens
670
+ for (let i = 0; i < requestParts.length; i++) {
671
+ const ctxToken = requestParts[i];
672
+ if (checkAsRouter && i >= pathTokens.length) {
673
+ break;
674
+ }
675
+
676
+ if (pathTokens[i].wild || ctxToken.lower === pathTokens[i].lower) {
677
+ // check pass
678
+ const wild = pathTokens[i].wild;
679
+ if (wild) {
680
+ params[wild] = ctxToken.value;
681
+ }
682
+ continue;
683
+ }
684
+
685
+ //console.log("matchTokenizePath(%s, %o, %o)=%s", checkAsRouter, pathTokens, requestParts, false);
686
+ return {
687
+ match: false,
688
+ params: {}
689
+ };
690
+ }
691
+ //console.log("matchTokenizePath(%s, %o, %o)=%s", checkAsRouter, pathTokens, requestParts, true);
692
+ return {
693
+ match: true,
694
+ params
695
+ };
696
+ } else {
697
+ //console.log("matchTokenizePath(%s, %o, %o)=%s", checkAsRouter, pathTokens, requestParts, false);
698
+ return {
699
+ match: false,
700
+ params: {}
701
+ };
702
+ }
703
+ }
704
+
705
+ export function newURL(input: string): URL {
706
+ /*
707
+ remove /+ at the start of the input before using new URL ( it changes the host )
708
+ */
709
+ let slashIndex = 0
710
+ for (slashIndex = 0; slashIndex < input.length; slashIndex++) {
711
+ if (input.charAt(slashIndex) !== "/") {
712
+ break;
713
+ }
714
+ }
715
+ const removedSlashes = input.substring(0, slashIndex - 1);
716
+ const ret = new URL(input.substring(slashIndex), "http://localhost");
717
+ // restore path
718
+ ret.pathname = `${slashIndex > 0 ? removedSlashes : ""}${ret.pathname}`;
719
+ return ret;
720
+ }
721
+
722
+ // adds "/" to the final of path
723
+ // cannot account for query or hash params so send only new URL().pathname
724
+ export function normalizePath(path: string): string {
725
+ if (typeof path !== "string") {
726
+ throw new Error("path not string");
727
+ }
728
+ if (path.length > 1) {
729
+ if (path.charAt(0) !== "/") {
730
+ throw new Error("path doesnt start with /");
731
+ }
732
+ if (path[path.length - 1] !== "/") {
733
+ return `${path}/`;
734
+ } else {
735
+ return path; // already normalized
736
+ }
737
+ } else if (path !== "/") {
738
+ throw new Error("path of length 1 not /");
739
+ } else {
740
+ return path; // "/"
741
+ }
742
+ }
743
+
744
+ export function parseSearchParams(search: URLSearchParams): { [name: string]: string | string[] } {
745
+ const query: { [name: string]: string | string[] } = Object.create(null);
746
+ search.forEach((value: string, key: string) => {
747
+ query[key] = query[key] instanceof Array ? (query[key] as string[]).concat([value]) : query[key] ? [query[key] as string, value] : value;
748
+ });
749
+ return query;
750
+ }
751
+
752
+ export interface ConnectionUpgrader {
753
+ onUpgrade: (req: Request, socket: Duplex, head: Buffer) => Promise<void> | void;
754
+ }
755
+
756
+ export interface WebSocketComplexValidateResult {
757
+ uuid?: string;
758
+ headers?: {
759
+ name: string;
760
+ value: string;
761
+ }[];
762
+ }
763
+
764
+ export interface WebSocketServerOptions {
765
+ maxConnections?: number;
766
+ validate?: (req: Request) => Promise<boolean | string | WebSocketComplexValidateResult> | boolean | string | WebSocketComplexValidateResult;
767
+ onConnection?: (req: WebSocketClient) => void;
768
+ onMessage?: (req: WebSocketClient, data: string | undefined | null) => void;
769
+ onDisconnect?: (req: WebSocketClient) => void;
770
+ logger?: {
771
+ log(message?: any, ...optionalParams: any[]): void;
772
+ info(message?: any, ...optionalParams: any[]): void;
773
+ trace(message?: any, ...optionalParams: any[]): void;
774
+ debug(message?: any, ...optionalParams: any[]): void;
775
+ warn(message?: any, ...optionalParams: any[]): void;
776
+ error(message?: any, ...optionalParams: any[]): void;
777
+ };
778
+ }
779
+
780
+ export interface WebSocketClient {
781
+ uuid: string;
782
+ req: Request;
783
+ socket: Duplex;
784
+ head: Buffer;
785
+ }