tezx 2.0.11 → 3.0.0

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 (234) hide show
  1. package/README.md +122 -89
  2. package/bun/getConnInfo.d.ts +21 -0
  3. package/bun/getConnInfo.js +9 -0
  4. package/bun/index.d.ts +10 -4
  5. package/bun/index.js +8 -4
  6. package/bun/ws.d.ts +48 -0
  7. package/bun/ws.js +58 -0
  8. package/cjs/bun/getConnInfo.js +12 -0
  9. package/cjs/bun/index.js +35 -7
  10. package/cjs/bun/ws.js +63 -0
  11. package/cjs/core/config.js +2 -12
  12. package/cjs/core/context.js +131 -379
  13. package/cjs/core/error.js +49 -0
  14. package/cjs/core/request.js +79 -131
  15. package/cjs/core/router.js +54 -387
  16. package/cjs/core/server.js +83 -202
  17. package/cjs/deno/env.js +4 -4
  18. package/cjs/deno/getConnInfo.js +18 -0
  19. package/cjs/deno/index.js +11 -18
  20. package/cjs/deno/serveStatic.js +53 -0
  21. package/cjs/deno/ws.js +39 -0
  22. package/cjs/helper/index.js +46 -10
  23. package/cjs/index.js +5 -7
  24. package/cjs/jwt/node.js +94 -0
  25. package/cjs/jwt/web.js +178 -0
  26. package/cjs/middleware/basic-auth.js +42 -0
  27. package/cjs/middleware/bearer-auth.js +34 -0
  28. package/cjs/middleware/cache-control.js +44 -0
  29. package/cjs/middleware/cors.js +11 -21
  30. package/cjs/middleware/detect-bot.js +57 -0
  31. package/cjs/middleware/i18n.js +73 -60
  32. package/cjs/middleware/index.js +8 -46
  33. package/cjs/middleware/logger.js +9 -4
  34. package/cjs/middleware/pagination.js +3 -2
  35. package/cjs/middleware/powered-by.js +3 -2
  36. package/cjs/middleware/rate-limiter.js +38 -0
  37. package/cjs/middleware/request-id.js +4 -5
  38. package/cjs/middleware/sanitize-headers.js +22 -0
  39. package/cjs/middleware/secure-headers copy.js +143 -0
  40. package/cjs/middleware/secure-headers.js +157 -0
  41. package/cjs/middleware/{xssProtection.js → xss-protection.js} +5 -8
  42. package/cjs/node/env.js +7 -7
  43. package/cjs/node/getConnInfo.js +16 -0
  44. package/cjs/node/index.js +17 -18
  45. package/cjs/node/mount-node.js +59 -0
  46. package/cjs/node/serveStatic.js +56 -0
  47. package/cjs/node/toWebRequest.js +25 -0
  48. package/cjs/node/ws.js +82 -0
  49. package/cjs/registry/RadixRouter.js +148 -0
  50. package/cjs/registry/index.js +17 -0
  51. package/cjs/types/headers.js +2 -0
  52. package/cjs/types/index.js +13 -0
  53. package/cjs/utils/buffer.js +17 -0
  54. package/cjs/utils/colors.js +2 -0
  55. package/cjs/utils/cookie.js +59 -0
  56. package/cjs/utils/file.js +136 -0
  57. package/cjs/utils/formData.js +60 -10
  58. package/cjs/utils/generateID.js +37 -0
  59. package/cjs/utils/low-level.js +115 -0
  60. package/cjs/utils/{staticFile.js → mimeTypes.js} +0 -87
  61. package/cjs/utils/rateLimit.js +41 -0
  62. package/cjs/utils/response.js +65 -0
  63. package/cjs/{core/environment.js → utils/runtime.js} +2 -1
  64. package/cjs/utils/url.js +65 -30
  65. package/core/config.d.ts +2 -7
  66. package/core/config.js +2 -12
  67. package/core/context.d.ts +209 -164
  68. package/core/context.js +131 -346
  69. package/core/error.d.ts +96 -0
  70. package/core/error.js +44 -0
  71. package/core/request.d.ts +67 -107
  72. package/core/request.js +78 -130
  73. package/core/router.d.ts +138 -133
  74. package/core/router.js +53 -352
  75. package/core/server.d.ts +99 -38
  76. package/core/server.js +83 -202
  77. package/deno/env.js +3 -3
  78. package/deno/getConnInfo.d.ts +21 -0
  79. package/deno/getConnInfo.js +15 -0
  80. package/deno/index.d.ts +9 -4
  81. package/deno/index.js +7 -4
  82. package/deno/serveStatic.d.ts +28 -0
  83. package/deno/serveStatic.js +49 -0
  84. package/deno/ws.d.ts +42 -0
  85. package/deno/ws.js +36 -0
  86. package/helper/index.d.ts +29 -15
  87. package/helper/index.js +27 -7
  88. package/index.d.ts +10 -8
  89. package/index.js +4 -5
  90. package/jwt/node.d.ts +39 -0
  91. package/jwt/node.js +87 -0
  92. package/jwt/web.d.ts +14 -0
  93. package/jwt/web.js +174 -0
  94. package/middleware/basic-auth.d.ts +56 -0
  95. package/middleware/basic-auth.js +38 -0
  96. package/middleware/bearer-auth.d.ts +53 -0
  97. package/middleware/bearer-auth.js +30 -0
  98. package/middleware/cache-control.d.ts +30 -0
  99. package/middleware/cache-control.js +40 -0
  100. package/middleware/cors.d.ts +30 -3
  101. package/middleware/cors.js +12 -22
  102. package/middleware/detect-bot.d.ts +113 -0
  103. package/middleware/detect-bot.js +53 -0
  104. package/middleware/i18n.d.ts +166 -73
  105. package/middleware/i18n.js +73 -60
  106. package/middleware/index.d.ts +8 -32
  107. package/middleware/index.js +8 -44
  108. package/middleware/logger.d.ts +5 -2
  109. package/middleware/logger.js +9 -4
  110. package/middleware/pagination.d.ts +9 -6
  111. package/middleware/pagination.js +3 -2
  112. package/middleware/powered-by.d.ts +2 -1
  113. package/middleware/powered-by.js +3 -2
  114. package/middleware/{rateLimiter.d.ts → rate-limiter.d.ts} +15 -9
  115. package/middleware/rate-limiter.js +34 -0
  116. package/middleware/request-id.d.ts +2 -1
  117. package/middleware/request-id.js +5 -6
  118. package/middleware/{sanitizeHeader.d.ts → sanitize-headers.d.ts} +5 -19
  119. package/middleware/sanitize-headers.js +18 -0
  120. package/middleware/secure-headers copy.d.ts +15 -0
  121. package/middleware/secure-headers copy.js +136 -0
  122. package/middleware/secure-headers.d.ts +132 -0
  123. package/middleware/secure-headers.js +153 -0
  124. package/middleware/{xssProtection.d.ts → xss-protection.d.ts} +2 -1
  125. package/middleware/xss-protection.js +19 -0
  126. package/node/env.js +4 -4
  127. package/node/getConnInfo.d.ts +21 -0
  128. package/node/getConnInfo.js +13 -0
  129. package/node/index.d.ts +13 -4
  130. package/node/index.js +11 -4
  131. package/node/mount-node.d.ts +11 -0
  132. package/node/mount-node.js +56 -0
  133. package/node/serveStatic.d.ts +36 -0
  134. package/node/serveStatic.js +52 -0
  135. package/node/toWebRequest.js +22 -0
  136. package/node/ws.d.ts +56 -0
  137. package/node/ws.js +46 -0
  138. package/package.json +39 -30
  139. package/registry/RadixRouter.d.ts +40 -0
  140. package/registry/RadixRouter.js +144 -0
  141. package/registry/index.d.ts +2 -0
  142. package/registry/index.js +1 -0
  143. package/types/headers.d.ts +2 -0
  144. package/types/headers.js +1 -0
  145. package/types/index.d.ts +318 -18
  146. package/types/index.js +12 -1
  147. package/utils/buffer.d.ts +1 -0
  148. package/utils/buffer.js +14 -0
  149. package/utils/colors.d.ts +24 -0
  150. package/utils/colors.js +2 -0
  151. package/utils/cookie.d.ts +55 -0
  152. package/utils/cookie.js +53 -0
  153. package/utils/file.d.ts +38 -0
  154. package/utils/file.js +96 -0
  155. package/utils/formData.d.ts +41 -1
  156. package/utils/formData.js +58 -9
  157. package/utils/generateID.d.ts +42 -0
  158. package/utils/generateID.js +32 -0
  159. package/utils/httpStatusMap.d.ts +14 -0
  160. package/utils/low-level.d.ts +58 -0
  161. package/utils/low-level.js +108 -0
  162. package/utils/mimeTypes.d.ts +4 -0
  163. package/utils/{staticFile.js → mimeTypes.js} +0 -53
  164. package/utils/rateLimit.d.ts +18 -0
  165. package/utils/rateLimit.js +37 -0
  166. package/utils/response.d.ts +18 -0
  167. package/utils/response.js +58 -0
  168. package/{core/environment.d.ts → utils/runtime.d.ts} +1 -0
  169. package/{core/environment.js → utils/runtime.js} +1 -0
  170. package/utils/url.d.ts +42 -14
  171. package/utils/url.js +61 -27
  172. package/bun/adapter.d.ts +0 -127
  173. package/bun/adapter.js +0 -97
  174. package/cjs/bun/adapter.js +0 -100
  175. package/cjs/core/MiddlewareConfigure.js +0 -68
  176. package/cjs/core/common.js +0 -15
  177. package/cjs/deno/adpater.js +0 -67
  178. package/cjs/helper/common.js +0 -17
  179. package/cjs/middleware/basicAuth.js +0 -71
  180. package/cjs/middleware/cacheControl.js +0 -90
  181. package/cjs/middleware/detectBot.js +0 -104
  182. package/cjs/middleware/detectLocale.js +0 -43
  183. package/cjs/middleware/lazyLoadModules.js +0 -73
  184. package/cjs/middleware/rateLimiter.js +0 -24
  185. package/cjs/middleware/requestTimeout.js +0 -42
  186. package/cjs/middleware/sanitizeHeader.js +0 -51
  187. package/cjs/middleware/secureHeaders.js +0 -42
  188. package/cjs/node/adapter.js +0 -138
  189. package/cjs/utils/regexRouter.js +0 -58
  190. package/cjs/utils/state.js +0 -34
  191. package/cjs/utils/toWebRequest.js +0 -35
  192. package/cjs/ws/deno.js +0 -20
  193. package/cjs/ws/index.js +0 -53
  194. package/cjs/ws/node.js +0 -65
  195. package/core/MiddlewareConfigure.d.ts +0 -15
  196. package/core/MiddlewareConfigure.js +0 -63
  197. package/core/common.d.ts +0 -21
  198. package/core/common.js +0 -11
  199. package/deno/adpater.d.ts +0 -38
  200. package/deno/adpater.js +0 -64
  201. package/helper/common.d.ts +0 -5
  202. package/helper/common.js +0 -14
  203. package/middleware/basicAuth.d.ts +0 -81
  204. package/middleware/basicAuth.js +0 -67
  205. package/middleware/cacheControl.d.ts +0 -48
  206. package/middleware/cacheControl.js +0 -53
  207. package/middleware/detectBot.d.ts +0 -121
  208. package/middleware/detectBot.js +0 -98
  209. package/middleware/detectLocale.d.ts +0 -55
  210. package/middleware/detectLocale.js +0 -39
  211. package/middleware/lazyLoadModules.d.ts +0 -72
  212. package/middleware/lazyLoadModules.js +0 -69
  213. package/middleware/rateLimiter.js +0 -20
  214. package/middleware/requestTimeout.d.ts +0 -25
  215. package/middleware/requestTimeout.js +0 -38
  216. package/middleware/sanitizeHeader.js +0 -47
  217. package/middleware/secureHeaders.d.ts +0 -78
  218. package/middleware/secureHeaders.js +0 -38
  219. package/middleware/xssProtection.js +0 -22
  220. package/node/adapter.d.ts +0 -46
  221. package/node/adapter.js +0 -102
  222. package/utils/regexRouter.d.ts +0 -66
  223. package/utils/regexRouter.js +0 -53
  224. package/utils/state.d.ts +0 -50
  225. package/utils/state.js +0 -30
  226. package/utils/staticFile.d.ts +0 -10
  227. package/utils/toWebRequest.js +0 -32
  228. package/ws/deno.d.ts +0 -6
  229. package/ws/deno.js +0 -16
  230. package/ws/index.d.ts +0 -180
  231. package/ws/index.js +0 -50
  232. package/ws/node.d.ts +0 -7
  233. package/ws/node.js +0 -28
  234. /package/{utils → node}/toWebRequest.d.ts +0 -0
package/types/index.d.ts CHANGED
@@ -1,27 +1,178 @@
1
- export type DuplicateMiddlewares = Middleware<any>[];
2
- export type UniqueMiddlewares = Set<Middleware<any>>;
1
+ /**
2
+ * Type definition for WebSocket event handlers.
3
+ * @template T - The type of data expected by the handler
4
+ * @param {WebSocket} ws - The WebSocket instance
5
+ * @param {T} [data] - Optional data associated with the event
6
+ * @returns {Promise<void> | void}
7
+ */
8
+ type WebSocketHandler<T = any> = (ws: WebSocket, data?: T) => Promise<void> | void;
9
+ /**
10
+ * Defines all supported WebSocket event handlers.
11
+ */
12
+ export type WebSocketEvent = {
13
+ /**
14
+ * Triggered when the WebSocket connection is successfully opened.(make sure it support in node)
15
+ */
16
+ open?: WebSocketHandler;
17
+ /**
18
+ * Triggered when a message is received from the client.
19
+ * Supports `string`, `Buffer`, or `ArrayBuffer` payloads.
20
+ */
21
+ message?: WebSocketHandler<string | Buffer | ArrayBuffer>;
22
+ /**
23
+ * Triggered when the WebSocket connection is closed.
24
+ * Provides the close code and reason.
25
+ */
26
+ close?: WebSocketHandler<{
27
+ code: number;
28
+ reason: string;
29
+ }>;
30
+ /**
31
+ * Triggered when an error occurs during the WebSocket lifecycle.
32
+ * Not supported in Bun.
33
+ */
34
+ error?: WebSocketHandler<Error | any>;
35
+ /**
36
+ * Triggered when the socket drain event occurs.
37
+ * Not supported in Deno and Node.
38
+ */
39
+ drain?: WebSocketHandler;
40
+ /**
41
+ * Triggered when a ping frame is received from the client.
42
+ * Not supported in Deno.
43
+ */
44
+ ping?: WebSocketHandler<Buffer>;
45
+ /**
46
+ * Triggered when a pong frame is received from the client.
47
+ * Not supported in Deno.
48
+ */
49
+ pong?: WebSocketHandler<Buffer>;
50
+ };
51
+ /**
52
+ * Callback function that returns WebSocket event handlers based on context.
53
+ * @param {Context} ctx - The request context
54
+ * @returns {WebSocketEvent} - Object containing WebSocket event handlers
55
+ */
56
+ export type WebSocketCallback = (ctx: Context) => WebSocketEvent;
57
+ /**
58
+ * Dynamic options for configuring WebSocket behavior across different runtimes.
59
+ */
60
+ export type WebSocketOptions = {
61
+ /**
62
+ * Called when an error occurs during the upgrade process.
63
+ */
64
+ onUpgradeError?: (err: TezXError, ctx: Context) => HttpBaseResponse;
65
+ };
66
+ /**
67
+ * Represents a string key used for HTTP headers.
68
+ */
69
+ export type ReqHeaderKey = RequestHeader | (string & {});
70
+ /**
71
+ * Represents a string key used for HTTP headers.
72
+ */
73
+ export type ResHeaderKey = ResponseHeader | (string & {});
74
+ /**
75
+ * Represents a collection of HTTP response headers as key-value pairs.
76
+ * Keys and values are strings.
77
+ */
78
+ export interface ResponseHeaders extends Partial<Record<ResHeaderKey, string>> {
79
+ [key: string]: string | undefined;
80
+ }
81
+ /**
82
+ * Represents a collection of HTTP request headers as key-value pairs.
83
+ * Keys and values are strings.
84
+ */
85
+ export interface RequestHeaders extends Partial<Record<ReqHeaderKey, string>> {
86
+ [key: string]: string | undefined;
87
+ }
88
+ /**
89
+ * Options for initializing a Response object.
90
+ */
91
+ export interface ResponseInit {
92
+ /**
93
+ * HTTP status code, e.g. 200, 404, 500.
94
+ * Optional; defaults to 200 if not specified.
95
+ */
96
+ status?: number;
97
+ /**
98
+ * Optional HTTP status text corresponding to the status code,
99
+ * e.g., "OK", "Not Found".
100
+ */
101
+ statusText?: string;
102
+ /**
103
+ * Additional HTTP response headers to include in the response.
104
+ */
105
+ headers?: ResponseHeaders;
106
+ }
107
+ /**
108
+ * Options for setting HTTP cookies.
109
+ */
3
110
  export interface CookieOptions {
111
+ /** Expiration date of the cookie. */
4
112
  expires?: Date;
113
+ /** URL path the cookie is valid for. */
5
114
  path?: string;
115
+ /** Max age of the cookie in seconds. */
6
116
  maxAge?: number;
117
+ /** Domain the cookie is valid for. */
7
118
  domain?: string;
119
+ /** Whether the cookie is only sent over HTTPS. */
8
120
  secure?: boolean;
121
+ /** Whether the cookie is inaccessible to JavaScript's `Document.cookie` API. */
9
122
  httpOnly?: boolean;
123
+ /** Controls cross-site request behavior. One of "Strict", "Lax", or "None". */
10
124
  sameSite?: "Strict" | "Lax" | "None";
11
125
  }
12
- export type AdapterType = "bun" | "deno" | "node";
13
- export type ResponseHeaders = Record<string, string>;
126
+ /**
127
+ * Represents the supported runtime adapter types.
128
+ */
129
+ export type Runtime = "bun" | "deno" | "node";
14
130
  import { Context } from "../core/context.js";
131
+ import { TezXError } from "../core/error.js";
132
+ import { RequestHeader, ResponseHeader } from "./headers.js";
133
+ /**
134
+ * Options to customize static file serving behavior.
135
+ */
15
136
  export type StaticServeOption = {
137
+ /** Optional cache-control header value for static files, e.g. "max-age=3600". */
16
138
  cacheControl?: string;
139
+ /** Additional HTTP headers to set on static file responses. */
17
140
  headers?: ResponseHeaders;
141
+ /**
142
+ * Allowed file extensions to serve.
143
+ * If provided, only files with these extensions will be served.
144
+ * Example: ["html", "css", "js", "png"]
145
+ */
146
+ extensions?: string[];
147
+ };
148
+ /**
149
+ * Represents the list of static files and their corresponding route paths.
150
+ */
151
+ export type StaticFileArray = {
152
+ /** Absolute path to the static file on the file system. */
153
+ fileSource: string;
154
+ /** Public route (URL path) where the file will be served. */
155
+ route: string;
156
+ }[];
157
+ /**
158
+ * Represents a static file configuration to be served by the server.
159
+ */
160
+ export type ServeStatic = {
161
+ /**
162
+ * Array of static files and their corresponding route paths.
163
+ */
164
+ files: StaticFileArray;
165
+ /**
166
+ * Optional settings to control caching, headers, and allowed extensions.
167
+ */
168
+ options?: StaticServeOption;
18
169
  };
19
170
  type ExtractParam<Path extends string> = Path extends `${infer _Start}:${infer Param}/${infer Rest}` ? Param extends `${infer Name}?` ? {
20
- [K in Name]?: string;
171
+ [K in Name]?: string | null;
21
172
  } & ExtractParam<`/${Rest}`> : {
22
173
  [K in Param]: string;
23
174
  } & ExtractParam<`/${Rest}`> : Path extends `${infer _Start}:${infer Param}` ? Param extends `${infer Name}?` ? {
24
- [K in Name]?: string;
175
+ [K in Name]?: string | null;
25
176
  } : {
26
177
  [K in Param]: string;
27
178
  } : {};
@@ -31,29 +182,178 @@ type ExtractWildcard<Path extends string> = Path extends `${string}*${infer Wild
31
182
  [K in Wildcard]: string;
32
183
  } : {};
33
184
  export type ExtractRouteParams<Path extends string> = ExtractParam<Path> & ExtractWildcard<Path> & Record<string, string>;
34
- export type ExtractParamsFromPath<Path extends PathType> = (Path extends string ? ExtractRouteParams<Path> : {}) & Record<string, string>;
35
- export type NextCallback = () => Promise<any>;
36
- export type CallbackReturn = Promise<Response> | Response;
37
- export type ctx<T extends Record<string, any> = {}, Path extends PathType = any> = Context<T, Path> & T;
38
- export type Callback<T extends Record<string, any> = {}, Path extends PathType = any> = (ctx: ctx<T, Path>) => CallbackReturn;
39
- export type Middleware<T extends Record<string, any> = {}, Path extends PathType = any> = (ctx: ctx<T, Path>, next: NextCallback) => Promise<Response | void> | Response | NextCallback;
40
- export type PathType = string | RegExp;
41
- export type FormDataOptions = {
42
- maxSize?: number;
43
- allowedTypes?: string[];
185
+ export type ExtractParamsFromPath<Path extends string> = (Path extends string ? ExtractRouteParams<Path> : {}) & Record<string, string>;
186
+ /**
187
+ * A function that continues the middleware chain.
188
+ *
189
+ * @returns A Promise that resolves when the next middleware completes.
190
+ */
191
+ export type NextCallback = () => Promise<void>;
192
+ /**
193
+ * Represents a base HTTP response.
194
+ * It can either be a `Response` object or a `Promise` resolving to a `Response`.
195
+ */
196
+ export type HttpBaseResponse = Response | Promise<Response>;
197
+ /**
198
+ * The context object (`ctx`) passed to all handlers and middleware.
199
+ *
200
+ * @template T - Custom environment or app-level data.
201
+ * @template Path - Type of the route path (optional).
202
+ */
203
+ export type Ctx<T extends Record<string, any> = {}, Path extends string = any> = Context<T, Path> & T & {
204
+ [key: string]: any;
205
+ };
206
+ /**
207
+ * A callback (handler) for a route.
208
+ *
209
+ * @template T - Context data type.
210
+ * @template Path - Type of the route path.
211
+ *
212
+ * @param ctx - The context object for the request.
213
+ * @returns An HTTP response or a promise that resolves to an HTTP response.
214
+ */
215
+ export type Callback<T extends Record<string, any> = {}, Path extends string = any> = (ctx: Ctx<T, Path>) => HttpBaseResponse;
216
+ /**
217
+ * Middleware function type used in TezX.
218
+ * Similar to Koa-style middleware with `next()` chaining.
219
+ *
220
+ * @template T - Context data type.
221
+ * @template Path - Type of the route path.
222
+ *
223
+ * @param ctx - The context object.
224
+ * @param next - A callback to call the next middleware in the chain.
225
+ * @returns An HTTP response, a promise, or a call to `next()`.
226
+ */
227
+ export type Middleware<T extends Record<string, any> = {}, Path extends string = any> = (ctx: Ctx<T, Path>, next: NextCallback) => HttpBaseResponse | Promise<HttpBaseResponse | void> | NextCallback;
228
+ /**
229
+ * Error handler function type.
230
+ *
231
+ * @template T - Context data type.
232
+ *
233
+ * @param err - The error that was thrown.
234
+ * @param ctx - The context object where the error occurred.
235
+ * @returns An HTTP response or a promise that resolves to an HTTP response.
236
+ */
237
+ export type ErrorHandler<T extends Record<string, any> = {}> = (err: TezXError, ctx: Ctx<T>) => HttpBaseResponse;
238
+ /**
239
+ * Configuration options for parsing and validating multipart/form-data.
240
+ */
241
+ export interface FormDataOptions {
242
+ /**
243
+ * If true, apply basic sanitization to incoming text fields.
244
+ */
44
245
  sanitized?: boolean;
246
+ /**
247
+ * Whitelisted MIME types for uploaded files (e.g. ["image/jpeg", "image/png"]).
248
+ */
249
+ allowedTypes?: string[];
250
+ /**
251
+ * Maximum **per-file** size in bytes.
252
+ */
253
+ maxSize?: number;
254
+ /**
255
+ * Maximum number of files allowed **per field**.
256
+ */
45
257
  maxFiles?: number;
46
- };
258
+ /**
259
+ * Maximum **combined** size of all uploaded files in bytes.
260
+ */
261
+ maxTotalSize?: number;
262
+ /**
263
+ * Maximum length of a **single text field** (in characters/bytes, depending on your parser).
264
+ */
265
+ maxFieldSize?: number;
266
+ }
267
+ /**
268
+ * Supported low-level transport types for network addresses.
269
+ */
47
270
  type TransportType = "tcp" | "udp" | "unix" | "pipe" | "unixpacket";
271
+ /**
272
+ * A normalized network address description.
273
+ */
48
274
  export type NetAddr = {
275
+ /** Transport protocol used by the connection. */
49
276
  transport?: TransportType;
277
+ /** Address family. */
50
278
  family?: "IPv4" | "IPv6" | "Unix";
279
+ /** The IP/Unix path/etc. */
51
280
  address?: string;
281
+ /** TCP/UDP port number (if applicable). */
52
282
  port?: number;
53
283
  };
284
+ /**
285
+ * Connection address metadata holding both local and remote endpoints.
286
+ */
54
287
  export type ConnAddress = {
288
+ /** Remote peer address information. */
55
289
  remoteAddr: NetAddr;
290
+ /** Local server address information. */
56
291
  localAddr: NetAddr;
57
292
  };
58
- export type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "OPTIONS" | "PATCH" | "HEAD" | "ALL" | "TRACE" | "CONNECT" | string;
293
+ /**
294
+ * List of built-in, first-class supported HTTP methods.
295
+ * "ALL" can be used to register a handler for every method.
296
+ */
297
+ export declare const httpMethod: readonly ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD", "ALL", "TRACE", "CONNECT"];
298
+ /**
299
+ * HTTP method type. Extensible to support custom verb strings.
300
+ */
301
+ export type HTTPMethod = (typeof httpMethod)[number] | (string & {});
302
+ /**
303
+ * The result returned when searching for a route match.
304
+ *
305
+ * @template T - The type of the request context environment.
306
+ */
307
+ export type RouteMatchResult<T extends Record<string, any> = any> = {
308
+ /**
309
+ * The HTTP method of the matched route (e.g., "GET", "POST").
310
+ */
311
+ method: HTTPMethod;
312
+ /**
313
+ * The middleware functions that will be executed for this route.
314
+ */
315
+ middlewares: Middleware<T>[];
316
+ /**
317
+ * The final route handlers (callbacks or middlewares) to be executed.
318
+ */
319
+ handlers: HandlerType<T>;
320
+ /**
321
+ * An object containing route parameters extracted from the URL.
322
+ * The values can be strings, null (for optional params), or undefined.
323
+ */
324
+ params: Record<string, string | null | undefined>;
325
+ };
326
+ /**
327
+ * The array type containing route handlers and middlewares for a route.
328
+ *
329
+ * @template T - The type of the request context environment.
330
+ */
331
+ export type HandlerType<T extends Record<string, any> = any> = (Callback<T> | Middleware<T>)[];
332
+ /**
333
+ * Interface representing a router.
334
+ *
335
+ * @template T - The type of the handler.
336
+ */
337
+ export interface RouteRegistry {
338
+ /**
339
+ * The name of the router.
340
+ */
341
+ name: string;
342
+ /**
343
+ * Registers a route or middleware for a specific HTTP method.
344
+ *
345
+ * @param method - HTTP method (e.g., "GET", "POST", or "ALL" for middleware)
346
+ * @param path - Route path (e.g., "/users", "/api")
347
+ * @param handlers - Array of middleware or callback handlers
348
+ */
349
+ addRoute<T extends Record<string, any> = any>(method: HTTPMethod, path: string, handler: HandlerType<T>): void;
350
+ /**
351
+ * Find a route based on the given method and path.
352
+ *
353
+ * @param method - The HTTP method (e.g., 'get', 'post').
354
+ * @param path - The path to match.
355
+ * @returns The result of the match.
356
+ */
357
+ search(method: HTTPMethod, path: string): RouteMatchResult;
358
+ }
59
359
  export {};
package/types/index.js CHANGED
@@ -1 +1,12 @@
1
- export {};
1
+ export const httpMethod = [
2
+ "GET",
3
+ "POST",
4
+ "PUT",
5
+ "DELETE",
6
+ "OPTIONS",
7
+ "PATCH",
8
+ "HEAD",
9
+ "ALL",
10
+ "TRACE",
11
+ "CONNECT",
12
+ ];
@@ -0,0 +1 @@
1
+ export declare function base64Decode(base64: string): string;
@@ -0,0 +1,14 @@
1
+ export function base64Decode(base64) {
2
+ const pad = base64.length % 4;
3
+ if (pad)
4
+ base64 += "=".repeat(4 - pad);
5
+ if (typeof Buffer !== "undefined") {
6
+ return Buffer.from(base64, "base64").toString("utf-8");
7
+ }
8
+ else if (typeof atob === "function") {
9
+ return new TextDecoder().decode(Uint8Array.from(atob(base64), (c) => c.charCodeAt(0)));
10
+ }
11
+ else {
12
+ throw new Error("Base64 decode not supported in this environment");
13
+ }
14
+ }
package/utils/colors.d.ts CHANGED
@@ -1,3 +1,14 @@
1
+ /**
2
+ * ANSI escape codes for terminal text formatting and colors.
3
+ *
4
+ * These codes can be used to style console output with colors,
5
+ * bold, underline, and background colors.
6
+ *
7
+ * @constant {Record<string, string>}
8
+ *
9
+ * @example
10
+ * console.log(COLORS.red, "This text is red", COLORS.reset);
11
+ */
1
12
  export declare const COLORS: {
2
13
  reset: string;
3
14
  bold: string;
@@ -18,5 +29,18 @@ export declare const COLORS: {
18
29
  bgMagenta: string;
19
30
  bgCyan: string;
20
31
  bgWhite: string;
32
+ orange: string;
33
+ bgOrange: string;
21
34
  };
35
+ /**
36
+ * Wraps the given text with ANSI color codes for terminal styling.
37
+ *
38
+ * @param {string | number} text - The text or number to be colored.
39
+ * @param {keyof typeof COLORS} color - The color key from the COLORS object.
40
+ * @returns {string} The input text wrapped with the specified ANSI color code and reset code.
41
+ *
42
+ * @example
43
+ * console.log(colorText("Hello World", "red"));
44
+ * // Output: (red colored "Hello World" in terminal)
45
+ */
22
46
  export declare function colorText(text: string | number, color: keyof typeof COLORS): string;
package/utils/colors.js CHANGED
@@ -18,6 +18,8 @@ export const COLORS = {
18
18
  bgMagenta: "\x1b[45m",
19
19
  bgCyan: "\x1b[46m",
20
20
  bgWhite: "\x1b[47m",
21
+ orange: "\x1b[38;2;255;88;30m",
22
+ bgOrange: "\x1b[48;2;255;88;30m",
21
23
  };
22
24
  export function colorText(text, color) {
23
25
  return `${COLORS[color]}${text}${COLORS.reset}`;
@@ -0,0 +1,55 @@
1
+ import { Context } from "../core/context.js";
2
+ import { CookieOptions } from "../types/index.js";
3
+ /**
4
+ * Get the value of a specific cookie by name from the request context.
5
+ *
6
+ * @param {Context} ctx - The context containing the request.
7
+ * @param {string} name - The name of the cookie to retrieve.
8
+ * @returns {string | undefined} The cookie value if found, otherwise undefined.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const sessionId = getCookie(ctx,"session_id");
13
+ * ```
14
+ */
15
+ export declare function getCookie(ctx: Context, name: string): string | undefined;
16
+ /**
17
+ * Parse all cookies from the request's "cookie" header into an object.
18
+ *
19
+ * @param {Context} ctx - The context containing the request.
20
+ * @returns {Record<string, string>} An object mapping cookie names to their decoded values.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * const cookies = allCookies(ctx);
25
+ * console.log(cookies["session_id"]);
26
+ * ```
27
+ */
28
+ export declare function allCookies(ctx: Context): Record<string, string>;
29
+ /**
30
+ * Set a cookie in the response headers.
31
+ *
32
+ * @param {Context} ctx - The context containing the response.
33
+ * @param {string} name - The name of the cookie to set.
34
+ * @param {string} value - The cookie value.
35
+ * @param {CookieOptions} [options] - Optional cookie settings like `maxAge`, `path`, `secure`, etc.
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * setCookie(ctx, "session_id", "abc123", { httpOnly: true, maxAge: 3600 });
40
+ * ```
41
+ */
42
+ export declare function setCookie(ctx: Context, name: string, value: string, options?: CookieOptions): void;
43
+ /**
44
+ * Delete a cookie by setting its expiration date in the past.
45
+ *
46
+ * @param {Context} ctx - The context containing the response.
47
+ * @param {string} name - The name of the cookie to delete.
48
+ * @param {CookieOptions} [options] - Optional settings such as `path` to ensure proper deletion.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * deleteCookie(ctx, "session_id");
53
+ * ```
54
+ */
55
+ export declare function deleteCookie(ctx: Context, name: string, options?: CookieOptions): void;
@@ -0,0 +1,53 @@
1
+ export function getCookie(ctx, name) {
2
+ return allCookies(ctx)?.[name];
3
+ }
4
+ export function allCookies(ctx) {
5
+ const cookieHeader = ctx.req.header("cookie");
6
+ const cookies = {};
7
+ if (!cookieHeader)
8
+ return cookies;
9
+ let start = 0;
10
+ let sep = -1;
11
+ const len = cookieHeader.length;
12
+ for (let i = 0; i <= len; i++) {
13
+ const ch = cookieHeader.charCodeAt(i) || 59;
14
+ if (ch === 61 && sep === -1) {
15
+ sep = i;
16
+ }
17
+ else if (ch === 59 || i === len) {
18
+ if (sep > -1) {
19
+ const key = cookieHeader.slice(start, sep).trim();
20
+ const value = cookieHeader.slice(sep + 1, i).trim();
21
+ cookies[key] = decodeURIComponent(value);
22
+ }
23
+ start = i + 1;
24
+ sep = -1;
25
+ }
26
+ }
27
+ ctx.cookies = cookies;
28
+ return cookies;
29
+ }
30
+ export function setCookie(ctx, name, value, options) {
31
+ ctx.setHeader("Set-Cookie", `${name}=${value}; ${serializeOptions(options ?? {})}`);
32
+ }
33
+ export function deleteCookie(ctx, name, options) {
34
+ ctx.setHeader("Set-Cookie", `${name}=; ${serializeOptions({ ...options, maxAge: 0, expires: new Date(0) })}`);
35
+ }
36
+ function serializeOptions(options) {
37
+ const parts = [];
38
+ if (options.maxAge)
39
+ parts.push(`Max-Age=${options.maxAge}`);
40
+ if (options.expires)
41
+ parts.push(`Expires=${options.expires.toUTCString()}`);
42
+ if (options.path)
43
+ parts.push(`Path=${options.path}`);
44
+ if (options.domain)
45
+ parts.push(`Domain=${options.domain}`);
46
+ if (options.secure)
47
+ parts.push(`Secure`);
48
+ if (options.httpOnly)
49
+ parts.push(`HttpOnly`);
50
+ if (options.sameSite)
51
+ parts.push(`SameSite=${options.sameSite}`);
52
+ return parts.join("; ");
53
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Check asynchronously if a file exists at the given path.
3
+ * Supports Node.js, Bun, and Deno runtimes.
4
+ *
5
+ * @param {string} path - The file path to check.
6
+ * @returns {Promise<boolean>} - Resolves to true if file exists, false otherwise.
7
+ */
8
+ export declare function fileExists(path: string): Promise<boolean>;
9
+ /**
10
+ * Asynchronously reads the entire file content as a Uint8Array.
11
+ * Supports Node.js, Bun, and Deno runtimes.
12
+ *
13
+ * @param {string} path - Path to the file.
14
+ * @returns {Promise<Uint8Array>} - Resolves to the file buffer.
15
+ * @throws Will throw an error if the runtime is unsupported.
16
+ */
17
+ export declare function getFileBuffer(path: string): Promise<Uint8Array>;
18
+ /**
19
+ * Creates a readable stream for the given file path.
20
+ * Supports Node.js, Bun, and Deno runtimes.
21
+ *
22
+ * @param {string} path - Path to the file.
23
+ * @returns {Promise<ReadableStream>} - Resolves to a ReadableStream of the file content.
24
+ * @throws Will throw an error if the runtime is unsupported.
25
+ */
26
+ export declare function readStream(path: string): Promise<ReadableStream>;
27
+ /**
28
+ * Asynchronously retrieves the size of a file in bytes.
29
+ * Supports Node.js, Bun, and Deno runtimes.
30
+ *
31
+ * @param {string} path - Path to the file.
32
+ * @returns {Promise<{size: number, mtime: Date}>} - Resolves to the file size in bytes.
33
+ */
34
+ export declare function fileSize(path: string): Promise<{
35
+ mtime: Date;
36
+ size: number;
37
+ }>;
38
+ export declare function etagDigest(algo: string | undefined, data: any): Promise<string>;