@catbee/utils 0.0.4 → 0.0.6

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 (213) hide show
  1. package/LICENSE +21 -201
  2. package/README.md +911 -242
  3. package/build/esm/config.d.ts +108 -8
  4. package/build/esm/config.js +122 -6
  5. package/build/esm/config.js.map +1 -1
  6. package/build/esm/index.d.ts +6 -0
  7. package/build/esm/index.js +29 -0
  8. package/build/esm/index.js.map +1 -1
  9. package/build/esm/servers/server.builder.d.ts +625 -0
  10. package/build/esm/servers/server.builder.js +722 -0
  11. package/build/esm/servers/server.builder.js.map +1 -0
  12. package/build/esm/servers/server.d.ts +256 -0
  13. package/build/esm/servers/server.js +1211 -0
  14. package/build/esm/servers/server.js.map +1 -0
  15. package/build/esm/types/api-response.d.ts +5 -7
  16. package/build/esm/types/api-response.js +23 -0
  17. package/build/esm/types/api-response.js.map +1 -1
  18. package/build/esm/types/index.d.ts +125 -0
  19. package/build/esm/types/index.js +25 -0
  20. package/build/esm/types/index.js.map +1 -0
  21. package/build/esm/types/server.d.ts +285 -0
  22. package/build/esm/types/server.js +25 -0
  23. package/build/esm/types/server.js.map +1 -0
  24. package/build/esm/utils/array.utils.js +23 -0
  25. package/build/esm/utils/array.utils.js.map +1 -1
  26. package/build/esm/utils/async.utils.js +23 -0
  27. package/build/esm/utils/async.utils.js.map +1 -1
  28. package/build/esm/utils/cache.utils.js +39 -16
  29. package/build/esm/utils/cache.utils.js.map +1 -1
  30. package/build/esm/utils/context-store.utils.d.ts +1 -1
  31. package/build/esm/utils/context-store.utils.js +24 -1
  32. package/build/esm/utils/context-store.utils.js.map +1 -1
  33. package/build/esm/utils/crypto.utils.js +26 -2
  34. package/build/esm/utils/crypto.utils.js.map +1 -1
  35. package/build/esm/utils/decorators.utils.d.ts +291 -0
  36. package/build/esm/utils/decorators.utils.js +395 -41
  37. package/build/esm/utils/decorators.utils.js.map +1 -1
  38. package/build/esm/utils/dir.utils.js +23 -0
  39. package/build/esm/utils/dir.utils.js.map +1 -1
  40. package/build/esm/utils/env.utils.d.ts +186 -23
  41. package/build/esm/utils/env.utils.js +517 -91
  42. package/build/esm/utils/env.utils.js.map +1 -1
  43. package/build/esm/utils/exception.utils.js +31 -8
  44. package/build/esm/utils/exception.utils.js.map +1 -1
  45. package/build/esm/utils/fs.utils.js +23 -0
  46. package/build/esm/utils/fs.utils.js.map +1 -1
  47. package/build/esm/utils/http-status-codes.js +23 -0
  48. package/build/esm/utils/http-status-codes.js.map +1 -1
  49. package/build/esm/utils/id.utils.js +23 -0
  50. package/build/esm/utils/id.utils.js.map +1 -1
  51. package/build/esm/utils/logger.utils.d.ts +118 -0
  52. package/build/esm/utils/logger.utils.js +251 -15
  53. package/build/esm/utils/logger.utils.js.map +1 -1
  54. package/build/esm/utils/middleware.utils.d.ts +29 -7
  55. package/build/esm/utils/middleware.utils.js +81 -55
  56. package/build/esm/utils/middleware.utils.js.map +1 -1
  57. package/build/esm/utils/obj.utils.d.ts +10 -3
  58. package/build/esm/utils/obj.utils.js +225 -15
  59. package/build/esm/utils/obj.utils.js.map +1 -1
  60. package/build/esm/utils/request.utils.d.ts +77 -0
  61. package/build/esm/utils/request.utils.js +196 -0
  62. package/build/esm/utils/request.utils.js.map +1 -0
  63. package/build/esm/utils/response.utils.d.ts +15 -1
  64. package/build/esm/utils/response.utils.js +55 -4
  65. package/build/esm/utils/response.utils.js.map +1 -1
  66. package/build/esm/utils/string.utils.js +23 -0
  67. package/build/esm/utils/string.utils.js.map +1 -1
  68. package/build/esm/utils/url.utils.js +23 -0
  69. package/build/esm/utils/url.utils.js.map +1 -1
  70. package/build/esm/utils/validate.utils.d.ts +7 -0
  71. package/build/esm/utils/validate.utils.js +35 -2
  72. package/build/esm/utils/validate.utils.js.map +1 -1
  73. package/build/esnext/config.d.ts +108 -8
  74. package/build/esnext/config.js +122 -6
  75. package/build/esnext/config.js.map +1 -1
  76. package/build/esnext/index.d.ts +6 -0
  77. package/build/esnext/index.js +29 -0
  78. package/build/esnext/index.js.map +1 -1
  79. package/build/esnext/servers/server.builder.d.ts +625 -0
  80. package/build/esnext/servers/server.builder.js +677 -0
  81. package/build/esnext/servers/server.builder.js.map +1 -0
  82. package/build/esnext/servers/server.d.ts +256 -0
  83. package/build/esnext/servers/server.js +918 -0
  84. package/build/esnext/servers/server.js.map +1 -0
  85. package/build/esnext/types/api-response.d.ts +5 -7
  86. package/build/esnext/types/api-response.js +23 -0
  87. package/build/esnext/types/api-response.js.map +1 -1
  88. package/build/esnext/types/index.d.ts +125 -0
  89. package/build/esnext/types/index.js +25 -0
  90. package/build/esnext/types/index.js.map +1 -0
  91. package/build/esnext/types/server.d.ts +285 -0
  92. package/build/esnext/types/server.js +25 -0
  93. package/build/esnext/types/server.js.map +1 -0
  94. package/build/esnext/utils/array.utils.js +23 -0
  95. package/build/esnext/utils/array.utils.js.map +1 -1
  96. package/build/esnext/utils/async.utils.js +23 -0
  97. package/build/esnext/utils/async.utils.js.map +1 -1
  98. package/build/esnext/utils/cache.utils.js +39 -16
  99. package/build/esnext/utils/cache.utils.js.map +1 -1
  100. package/build/esnext/utils/context-store.utils.d.ts +1 -1
  101. package/build/esnext/utils/context-store.utils.js +24 -1
  102. package/build/esnext/utils/context-store.utils.js.map +1 -1
  103. package/build/esnext/utils/crypto.utils.js +26 -2
  104. package/build/esnext/utils/crypto.utils.js.map +1 -1
  105. package/build/esnext/utils/decorators.utils.d.ts +291 -0
  106. package/build/esnext/utils/decorators.utils.js +371 -22
  107. package/build/esnext/utils/decorators.utils.js.map +1 -1
  108. package/build/esnext/utils/dir.utils.js +23 -0
  109. package/build/esnext/utils/dir.utils.js.map +1 -1
  110. package/build/esnext/utils/env.utils.d.ts +186 -23
  111. package/build/esnext/utils/env.utils.js +468 -77
  112. package/build/esnext/utils/env.utils.js.map +1 -1
  113. package/build/esnext/utils/exception.utils.js +30 -7
  114. package/build/esnext/utils/exception.utils.js.map +1 -1
  115. package/build/esnext/utils/fs.utils.js +23 -0
  116. package/build/esnext/utils/fs.utils.js.map +1 -1
  117. package/build/esnext/utils/http-status-codes.js +23 -0
  118. package/build/esnext/utils/http-status-codes.js.map +1 -1
  119. package/build/esnext/utils/id.utils.js +23 -0
  120. package/build/esnext/utils/id.utils.js.map +1 -1
  121. package/build/esnext/utils/logger.utils.d.ts +118 -0
  122. package/build/esnext/utils/logger.utils.js +222 -15
  123. package/build/esnext/utils/logger.utils.js.map +1 -1
  124. package/build/esnext/utils/middleware.utils.d.ts +29 -7
  125. package/build/esnext/utils/middleware.utils.js +77 -55
  126. package/build/esnext/utils/middleware.utils.js.map +1 -1
  127. package/build/esnext/utils/obj.utils.d.ts +10 -3
  128. package/build/esnext/utils/obj.utils.js +176 -12
  129. package/build/esnext/utils/obj.utils.js.map +1 -1
  130. package/build/esnext/utils/request.utils.d.ts +77 -0
  131. package/build/esnext/utils/request.utils.js +168 -0
  132. package/build/esnext/utils/request.utils.js.map +1 -0
  133. package/build/esnext/utils/response.utils.d.ts +15 -1
  134. package/build/esnext/utils/response.utils.js +55 -4
  135. package/build/esnext/utils/response.utils.js.map +1 -1
  136. package/build/esnext/utils/string.utils.js +23 -0
  137. package/build/esnext/utils/string.utils.js.map +1 -1
  138. package/build/esnext/utils/url.utils.js +23 -0
  139. package/build/esnext/utils/url.utils.js.map +1 -1
  140. package/build/esnext/utils/validate.utils.d.ts +7 -0
  141. package/build/esnext/utils/validate.utils.js +33 -0
  142. package/build/esnext/utils/validate.utils.js.map +1 -1
  143. package/build/src/config.d.ts +108 -8
  144. package/build/src/config.js +125 -7
  145. package/build/src/config.js.map +1 -1
  146. package/build/src/index.d.ts +6 -0
  147. package/build/src/index.js +32 -0
  148. package/build/src/index.js.map +1 -1
  149. package/build/src/servers/server.builder.d.ts +625 -0
  150. package/build/src/servers/server.builder.js +681 -0
  151. package/build/src/servers/server.builder.js.map +1 -0
  152. package/build/src/servers/server.d.ts +256 -0
  153. package/build/src/servers/server.js +958 -0
  154. package/build/src/servers/server.js.map +1 -0
  155. package/build/src/types/api-response.d.ts +5 -7
  156. package/build/src/types/api-response.js +23 -0
  157. package/build/src/types/api-response.js.map +1 -1
  158. package/build/src/types/index.d.ts +125 -0
  159. package/build/src/types/index.js +26 -0
  160. package/build/src/types/index.js.map +1 -0
  161. package/build/src/types/server.d.ts +285 -0
  162. package/build/src/types/server.js +26 -0
  163. package/build/src/types/server.js.map +1 -0
  164. package/build/src/utils/array.utils.js +23 -0
  165. package/build/src/utils/array.utils.js.map +1 -1
  166. package/build/src/utils/async.utils.js +23 -0
  167. package/build/src/utils/async.utils.js.map +1 -1
  168. package/build/src/utils/cache.utils.js +38 -15
  169. package/build/src/utils/cache.utils.js.map +1 -1
  170. package/build/src/utils/context-store.utils.d.ts +1 -1
  171. package/build/src/utils/context-store.utils.js +24 -1
  172. package/build/src/utils/context-store.utils.js.map +1 -1
  173. package/build/src/utils/crypto.utils.js +25 -1
  174. package/build/src/utils/crypto.utils.js.map +1 -1
  175. package/build/src/utils/decorators.utils.d.ts +291 -0
  176. package/build/src/utils/decorators.utils.js +373 -22
  177. package/build/src/utils/decorators.utils.js.map +1 -1
  178. package/build/src/utils/dir.utils.js +23 -0
  179. package/build/src/utils/dir.utils.js.map +1 -1
  180. package/build/src/utils/env.utils.d.ts +186 -23
  181. package/build/src/utils/env.utils.js +467 -76
  182. package/build/src/utils/env.utils.js.map +1 -1
  183. package/build/src/utils/exception.utils.js +30 -7
  184. package/build/src/utils/exception.utils.js.map +1 -1
  185. package/build/src/utils/fs.utils.js +23 -0
  186. package/build/src/utils/fs.utils.js.map +1 -1
  187. package/build/src/utils/http-status-codes.js +23 -0
  188. package/build/src/utils/http-status-codes.js.map +1 -1
  189. package/build/src/utils/id.utils.js +23 -0
  190. package/build/src/utils/id.utils.js.map +1 -1
  191. package/build/src/utils/logger.utils.d.ts +118 -0
  192. package/build/src/utils/logger.utils.js +228 -15
  193. package/build/src/utils/logger.utils.js.map +1 -1
  194. package/build/src/utils/middleware.utils.d.ts +29 -7
  195. package/build/src/utils/middleware.utils.js +76 -54
  196. package/build/src/utils/middleware.utils.js.map +1 -1
  197. package/build/src/utils/obj.utils.d.ts +10 -3
  198. package/build/src/utils/obj.utils.js +177 -12
  199. package/build/src/utils/obj.utils.js.map +1 -1
  200. package/build/src/utils/request.utils.d.ts +77 -0
  201. package/build/src/utils/request.utils.js +175 -0
  202. package/build/src/utils/request.utils.js.map +1 -0
  203. package/build/src/utils/response.utils.d.ts +15 -1
  204. package/build/src/utils/response.utils.js +56 -4
  205. package/build/src/utils/response.utils.js.map +1 -1
  206. package/build/src/utils/string.utils.js +23 -0
  207. package/build/src/utils/string.utils.js.map +1 -1
  208. package/build/src/utils/url.utils.js +23 -0
  209. package/build/src/utils/url.utils.js.map +1 -1
  210. package/build/src/utils/validate.utils.d.ts +7 -0
  211. package/build/src/utils/validate.utils.js +36 -2
  212. package/build/src/utils/validate.utils.js.map +1 -1
  213. package/package.json +40 -9
@@ -1,10 +1,45 @@
1
- /* eslint-disable @typescript-eslint/no-unused-vars */
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
2
24
  import 'reflect-metadata';
3
- // --- End sample Express interfaces ---
25
+ import { HttpStatusCodes } from './http-status-codes';
26
+ import { ForbiddenException } from './exception.utils';
27
+ // Metadata keys
4
28
  const ROUTES_KEY = Symbol('routes');
5
29
  const MIDDLEWARE_KEY = Symbol('middlewares');
6
30
  const PARAMS_KEY = Symbol('params');
7
- // ---- Route Decorators ----
31
+ const HTTP_CODE_KEY = Symbol('httpCode');
32
+ const HEADER_KEY = Symbol('headers');
33
+ const BEFORE_KEY = Symbol('before');
34
+ const AFTER_KEY = Symbol('after');
35
+ const ROLES_KEY = Symbol('roles');
36
+ const REDIRECT_KEY = Symbol('redirect');
37
+ /**
38
+ * Factory function that creates HTTP method decorators.
39
+ *
40
+ * @param method - HTTP method to create decorator for
41
+ * @returns A method decorator function
42
+ */
8
43
  function createRouteDecorator(method) {
9
44
  return (path) => {
10
45
  return (target, propertyKey, descriptor) => {
@@ -18,29 +53,134 @@ function createRouteDecorator(method) {
18
53
  };
19
54
  };
20
55
  }
56
+ /**
57
+ * Decorator for GET HTTP method routes.
58
+ *
59
+ * @param path - URL path for the route
60
+ * @returns Method decorator
61
+ *
62
+ * @example
63
+ * ```ts
64
+ * @Get('/users')
65
+ * getUsers() {
66
+ * return this.userService.findAll();
67
+ * }
68
+ * ```
69
+ */
21
70
  export const Get = createRouteDecorator('get');
71
+ /**
72
+ * Decorator for POST HTTP method routes.
73
+ *
74
+ * @param path - URL path for the route
75
+ * @returns Method decorator
76
+ *
77
+ * @example
78
+ * ```ts
79
+ * @Post('/users')
80
+ * createUser(@Body() userData: any) {
81
+ * return this.userService.create(userData);
82
+ * }
83
+ * ```
84
+ */
22
85
  export const Post = createRouteDecorator('post');
86
+ /**
87
+ * Decorator for PUT HTTP method routes.
88
+ *
89
+ * @param path - URL path for the route
90
+ * @returns Method decorator
91
+ */
23
92
  export const Put = createRouteDecorator('put');
93
+ /**
94
+ * Decorator for PATCH HTTP method routes.
95
+ *
96
+ * @param path - URL path for the route
97
+ * @returns Method decorator
98
+ */
24
99
  export const Patch = createRouteDecorator('patch');
100
+ /**
101
+ * Decorator for DELETE HTTP method routes.
102
+ *
103
+ * @param path - URL path for the route
104
+ * @returns Method decorator
105
+ */
25
106
  export const Delete = createRouteDecorator('delete');
107
+ /**
108
+ * Decorator for OPTIONS HTTP method routes.
109
+ *
110
+ * @param path - URL path for the route
111
+ * @returns Method decorator
112
+ */
26
113
  export const Options = createRouteDecorator('options');
114
+ /**
115
+ * Decorator for HEAD HTTP method routes.
116
+ *
117
+ * @param path - URL path for the route
118
+ * @returns Method decorator
119
+ */
27
120
  export const Head = createRouteDecorator('head');
121
+ /**
122
+ * Decorator for TRACE HTTP method routes.
123
+ *
124
+ * @param path - URL path for the route
125
+ * @returns Method decorator
126
+ */
28
127
  export const Trace = createRouteDecorator('trace');
128
+ /**
129
+ * Decorator for CONNECT HTTP method routes.
130
+ *
131
+ * @param path - URL path for the route
132
+ * @returns Method decorator
133
+ */
29
134
  export const Connect = createRouteDecorator('connect');
30
- // ---- Controller Decorator ----
135
+ /**
136
+ * Decorator that marks a class as a controller with a base path.
137
+ * Used as the entry point for routing configuration.
138
+ *
139
+ * @param basePath - Base URL path for all routes in this controller
140
+ * @returns Class decorator
141
+ *
142
+ * @example
143
+ * ```ts
144
+ * @Controller('/api/users')
145
+ * class UserController {
146
+ * // Controller methods...
147
+ * }
148
+ * ```
149
+ */
31
150
  export function Controller(basePath) {
32
151
  return target => {
33
152
  Reflect.defineMetadata('basePath', basePath, target);
34
153
  };
35
154
  }
36
- // ---- Middleware Decorator ----
155
+ /**
156
+ * Decorator that applies middleware to a controller method.
157
+ * Multiple middlewares can be applied and will execute in order.
158
+ *
159
+ * @param middlewares - Express middleware functions to apply
160
+ * @returns Method decorator
161
+ *
162
+ * @example
163
+ * ```ts
164
+ * @Get('/protected')
165
+ * @Use(authMiddleware, loggingMiddleware)
166
+ * getProtectedResource() {
167
+ * // This route is protected by auth middleware
168
+ * }
169
+ * ```
170
+ */
37
171
  export function Use(...middlewares) {
38
- return (target, propertyKey, descriptor) => {
172
+ return (target, propertyKey, _descriptor) => {
39
173
  const existing = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey) || [];
40
174
  Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey);
41
175
  };
42
176
  }
43
- // ---- Parameter Decorators ----
177
+ /**
178
+ * Factory function that creates parameter decorators.
179
+ *
180
+ * @param type - Parameter type to extract from request
181
+ * @param key - Optional fixed key for extraction
182
+ * @returns Parameter decorator function
183
+ */
44
184
  function createParamDecorator(type, key) {
45
185
  return (paramKey) => {
46
186
  return (target, propertyKey, parameterIndex) => {
@@ -52,45 +192,237 @@ function createParamDecorator(type, key) {
52
192
  };
53
193
  };
54
194
  }
195
+ /**
196
+ * Decorator that extracts query parameters from request.
197
+ *
198
+ * @param paramKey - Optional key to extract specific query parameter
199
+ * @returns Parameter decorator
200
+ *
201
+ * @example
202
+ * ```ts
203
+ * @Get('/search')
204
+ * search(@Query('term') searchTerm: string) {
205
+ * // searchTerm will contain the value of req.query.term
206
+ * }
207
+ * ```
208
+ */
55
209
  export const Query = createParamDecorator('query');
210
+ /**
211
+ * Decorator that extracts route parameters from request.
212
+ *
213
+ * @param paramKey - Optional key to extract specific route parameter
214
+ * @returns Parameter decorator
215
+ *
216
+ * @example
217
+ * ```ts
218
+ * @Get('/users/:id')
219
+ * getUser(@Param('id') userId: string) {
220
+ * // userId will contain the value of req.params.id
221
+ * }
222
+ * ```
223
+ */
56
224
  export const Param = createParamDecorator('param');
225
+ /**
226
+ * Decorator that extracts body or body property from request.
227
+ *
228
+ * @param paramKey - Optional key to extract specific body property
229
+ * @returns Parameter decorator
230
+ *
231
+ * @example
232
+ * ```ts
233
+ * @Post('/users')
234
+ * createUser(@Body() userData: any) {
235
+ * // userData will contain the entire req.body
236
+ * }
237
+ *
238
+ * @Post('/update')
239
+ * updateName(@Body('name') name: string) {
240
+ * // name will contain the value of req.body.name
241
+ * }
242
+ * ```
243
+ */
57
244
  export const Body = createParamDecorator('body');
245
+ /**
246
+ * Decorator that injects the entire request object.
247
+ *
248
+ * @returns Parameter decorator
249
+ *
250
+ * @example
251
+ * ```ts
252
+ * @Get('/complex')
253
+ * complex(@Req() req: Request) {
254
+ * // Access the full request object
255
+ * console.log(req.headers);
256
+ * }
257
+ * ```
258
+ */
58
259
  export const Req = createParamDecorator('req');
260
+ /**
261
+ * Decorator that injects the response object.
262
+ *
263
+ * @returns Parameter decorator
264
+ *
265
+ * @example
266
+ * ```ts
267
+ * @Get('/custom')
268
+ * custom(@Res() res: Response) {
269
+ * // Direct access to response object
270
+ * return res.status(201).send('Created');
271
+ * }
272
+ * ```
273
+ */
59
274
  export const Res = createParamDecorator('res');
60
- // Custom HTTP status code decorator
61
- const HTTP_CODE_KEY = Symbol('httpCode');
275
+ /**
276
+ * Decorator that sets a custom HTTP status code for a response.
277
+ *
278
+ * @param status - HTTP status code to use
279
+ * @returns Method decorator
280
+ *
281
+ * @example
282
+ * ```ts
283
+ * @Post('/users')
284
+ * @HttpCode(201)
285
+ * createUser(@Body() userData: any) {
286
+ * // Response will have 201 Created status code
287
+ * return { id: '123', ...userData };
288
+ * }
289
+ * ```
290
+ */
62
291
  export function HttpCode(status) {
63
- return (target, propertyKey, descriptor) => {
292
+ return (target, propertyKey, _descriptor) => {
64
293
  Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey);
65
294
  };
66
295
  }
67
- // Custom header decorator
68
- const HEADER_KEY = Symbol('headers');
296
+ /**
297
+ * Decorator that adds a custom HTTP header to the response.
298
+ *
299
+ * @param name - Header name
300
+ * @param value - Header value
301
+ * @returns Method decorator
302
+ *
303
+ * @example
304
+ * ```ts
305
+ * @Get('/data')
306
+ * @Header('Cache-Control', 'max-age=60')
307
+ * getData() {
308
+ * // Response will include the Cache-Control header
309
+ * return { data: '...' };
310
+ * }
311
+ * ```
312
+ */
69
313
  export function Header(name, value) {
70
- return (target, propertyKey, descriptor) => {
314
+ return (target, propertyKey, _descriptor) => {
71
315
  const headers = Reflect.getMetadata(HEADER_KEY, target, propertyKey) || {};
72
316
  headers[name] = value;
73
317
  Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey);
74
318
  };
75
319
  }
76
- // Before/After hooks (not Express middleware, but can be used for logging, etc.)
77
- const BEFORE_KEY = Symbol('before');
78
- const AFTER_KEY = Symbol('after');
320
+ /**
321
+ * Decorator that registers a function to run before route handler execution.
322
+ * Useful for pre-processing or logging.
323
+ *
324
+ * @param fn - Function to execute before the handler
325
+ * @returns Method decorator
326
+ *
327
+ * @example
328
+ * ```ts
329
+ * @Get('/users/:id')
330
+ * @Before((req, res) => console.log(`Accessing user ${req.params.id}`))
331
+ * getUser(@Param('id') id: string) {
332
+ * // Function will log before this handler runs
333
+ * }
334
+ * ```
335
+ */
79
336
  export function Before(fn) {
80
- return (target, propertyKey, descriptor) => {
337
+ return (target, propertyKey, _descriptor) => {
81
338
  const hooks = Reflect.getMetadata(BEFORE_KEY, target, propertyKey) || [];
82
339
  hooks.push(fn);
83
340
  Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey);
84
341
  };
85
342
  }
343
+ /**
344
+ * Decorator that registers a function to run after route handler execution.
345
+ * Can access the handler's result.
346
+ *
347
+ * @param fn - Function to execute after the handler
348
+ * @returns Method decorator
349
+ *
350
+ * @example
351
+ * ```ts
352
+ * @Get('/users/:id')
353
+ * @After((req, res, result) => console.log(`User data sent: ${JSON.stringify(result)}`))
354
+ * getUser(@Param('id') id: string) {
355
+ * // After this handler, the function will log the returned data
356
+ * return { id, name: 'Example' };
357
+ * }
358
+ * ```
359
+ */
86
360
  export function After(fn) {
87
- return (target, propertyKey, descriptor) => {
361
+ return (target, propertyKey, _descriptor) => {
88
362
  const hooks = Reflect.getMetadata(AFTER_KEY, target, propertyKey) || [];
89
363
  hooks.push(fn);
90
364
  Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey);
91
365
  };
92
366
  }
93
- // ---- Register Controllers ----
367
+ /**
368
+ * Decorator that requires specific roles for accessing a route.
369
+ * Must be used with authentication middleware.
370
+ *
371
+ * @param roles - List of roles that can access this route
372
+ * @returns Method decorator
373
+ *
374
+ * @example
375
+ * ```ts
376
+ * @Get('/admin/settings')
377
+ * @Roles('admin', 'superuser')
378
+ * getSettings() {
379
+ * // Only admins and superusers can access
380
+ * return { settings: [...] };
381
+ * }
382
+ * ```
383
+ */
384
+ export function Roles(...roles) {
385
+ return (target, propertyKey, _descriptor) => {
386
+ Reflect.defineMetadata(ROLES_KEY, roles, target, propertyKey);
387
+ };
388
+ }
389
+ /**
390
+ * Decorator that redirects to another URL.
391
+ *
392
+ * @param url - URL to redirect to (can be absolute or relative)
393
+ * @param statusCode - HTTP status code for redirect (default: 302)
394
+ * @returns Method decorator
395
+ *
396
+ * @example
397
+ * ```ts
398
+ * @Get('/old-path')
399
+ * @Redirect('/new-path', 301)
400
+ * redirectToNewPath() {
401
+ * // This method won't be executed; automatic redirect happens
402
+ * }
403
+ *
404
+ * @Get('/dynamic-redirect')
405
+ * @Redirect()
406
+ * getDynamicRedirect() {
407
+ * // Return an object with url and optionally statusCode
408
+ * return { url: '/calculated-path', statusCode: 307 };
409
+ * }
410
+ * ```
411
+ */
412
+ export function Redirect(url, statusCode = 302) {
413
+ return (target, propertyKey, descriptor) => {
414
+ // Store the redirect information in metadata
415
+ Reflect.defineMetadata(REDIRECT_KEY, { url, statusCode }, target, propertyKey);
416
+ return descriptor;
417
+ };
418
+ }
419
+ /**
420
+ * Registers all controller classes with the provided router.
421
+ * This function processes all decorators and sets up the Express routes.
422
+ *
423
+ * @param router - Express router instance
424
+ * @param controllers - Array of controller classes
425
+ */
94
426
  export function registerControllers(router, controllers) {
95
427
  controllers.forEach(ControllerClass => {
96
428
  const instance = new ControllerClass();
@@ -103,9 +435,20 @@ export function registerControllers(router, controllers) {
103
435
  const headers = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};
104
436
  const beforeHooks = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];
105
437
  const afterHooks = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];
438
+ const roles = Reflect.getMetadata(ROLES_KEY, instance, handlerName) || [];
439
+ const redirect = Reflect.getMetadata(REDIRECT_KEY, instance, handlerName);
106
440
  const handler = async (req, res, next) => {
107
- var _a, _b;
441
+ var _a, _b, _c, _d;
108
442
  try {
443
+ // Handle roles-based access control
444
+ if (roles.length && !((_b = (_a = req === null || req === void 0 ? void 0 : req.user) === null || _a === void 0 ? void 0 : _a.roles) === null || _b === void 0 ? void 0 : _b.some((role) => roles.includes(role)))) {
445
+ res.status(HttpStatusCodes.FORBIDDEN).json(new ForbiddenException('Forbidden Insufficient Roles'));
446
+ return;
447
+ }
448
+ // Process static redirect if configured
449
+ if (redirect && redirect.url) {
450
+ return res.redirect(redirect.statusCode, redirect.url);
451
+ }
109
452
  for (const fn of beforeHooks)
110
453
  await fn(req, res);
111
454
  const args = [];
@@ -134,11 +477,17 @@ export function registerControllers(router, controllers) {
134
477
  const result = instance[handlerName](...args);
135
478
  // Support both sync and async handlers
136
479
  const awaited = result instanceof Promise ? await result : result;
480
+ // Handle dynamic redirects
481
+ if (redirect && awaited && typeof awaited === 'object' && 'url' in awaited) {
482
+ const redirectUrl = awaited.url;
483
+ const redirectStatus = awaited.statusCode || redirect.statusCode;
484
+ return res.redirect(redirectStatus, redirectUrl);
485
+ }
137
486
  if (!res.headersSent && typeof awaited !== 'undefined') {
138
487
  if (httpCode)
139
- (_a = res.status) === null || _a === void 0 ? void 0 : _a.call(res, httpCode);
488
+ (_c = res.status) === null || _c === void 0 ? void 0 : _c.call(res, httpCode);
140
489
  for (const [k, v] of Object.entries(headers))
141
- (_b = res.set) === null || _b === void 0 ? void 0 : _b.call(res, k, v);
490
+ (_d = res.set) === null || _d === void 0 ? void 0 : _d.call(res, k, v);
142
491
  res.json(awaited);
143
492
  }
144
493
  for (const fn of afterHooks)
@@ -1 +1 @@
1
- {"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":"AAAA,sDAAsD;AAGtD,OAAO,kBAAkB,CAAC;AAE1B,wCAAwC;AAExC,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC7C,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AAgBpC,6BAA6B;AAC7B,SAAS,oBAAoB,CAAC,MAAkB;IAC9C,OAAO,CAAC,IAAY,EAAmB,EAAE;QACvC,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE;YACzC,MAAM,MAAM,GAAsB,OAAO,CAAC,WAAW,CAAC,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC;YAC5F,MAAM,CAAC,IAAI,CAAC;gBACV,IAAI;gBACJ,MAAM;gBACN,WAAW,EAAE,WAAqB;aACnC,CAAC,CAAC;YACH,OAAO,CAAC,cAAc,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,WAAW,CAAC,CAAC;QACjE,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,MAAM,GAAG,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,IAAI,GAAG,oBAAoB,CAAC,MAAM,CAAC,CAAC;AACjD,MAAM,CAAC,MAAM,GAAG,GAAG,oBAAoB,CAAC,KAAK,CAAC,CAAC;AAC/C,MAAM,CAAC,MAAM,KAAK,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;AACnD,MAAM,CAAC,MAAM,MA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C;wBAC9D,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBACpB,CAAC;oBACD,KAAK,MAAM,EAAE,IAAI,UAAU;wBAAE,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC3D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type { RequestHandler, Router } from 'express';\nimport 'reflect-metadata';\n\n// --- End sample Express interfaces ---\n\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\n\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\ninterface RouteDefinition {\n path: string;\n method: HttpMethod;\n handlerName: string;\n}\n\ninterface ParamDefinition {\n index: number;\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n key?: string;\n}\n\n// ---- Route Decorators ----\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\nexport const Get = createRouteDecorator('get');\nexport const Post = createRouteDecorator('post');\nexport const Put = createRouteDecorator('put');\nexport const Patch = createRouteDecorator('patch');\nexport const Delete = createRouteDecorator('delete');\nexport const Options = createRouteDecorator('options');\nexport const Head = createRouteDecorator('head');\nexport const Trace = createRouteDecorator('trace');\nexport const Connect = createRouteDecorator('connect');\n\n// ---- Controller Decorator ----\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n// ---- Middleware Decorator ----\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n// ---- Parameter Decorators ----\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\nexport const Query = createParamDecorator('query');\nexport const Param = createParamDecorator('param');\nexport const Body = createParamDecorator('body');\nexport const Req = createParamDecorator('req');\nexport const Res = createParamDecorator('res');\n\n// Custom HTTP status code decorator\nconst HTTP_CODE_KEY = Symbol('httpCode');\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n// Custom header decorator\nconst HEADER_KEY = Symbol('headers');\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n// Before/After hooks (not Express middleware, but can be used for logging, etc.)\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n// ---- Register Controllers ----\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
1
+ {"version":3,"file":"decorators.utils.js","sourceRoot":"","sources":["../../../src/utils/decorators.utils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAKH,OAAO,kBAAkB,CAAC;AAC1B,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEvD,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,cAAc,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC7C,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,aAAa,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AACzC,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AACrC,MAAM,UAAU,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAClC,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAClC,MAAM,YAAY,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AA+BxC;;;;;GAKG;AACH,SAAS,oBAAoB,CAAC,MAAkB;IAC9C,OAAO,CAAC,IAAY,EAAmB,EAAE;QACvC,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,EAAE;YACzC,MAAM,MAAM,GAAsB,OAAO,CAAC,WAAW,CAAC,UAAU,EAAE,MAAM,CAAC,WAAW,CAAC,IAAI,E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;oBACpB,CAAC;oBACD,KAAK,MAAM,EAAE,IAAI,UAAU;wBAAE,MAAM,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC;gBAC3D,CAAC;gBAAC,OAAO,GAAG,EAAE,CAAC;oBACb,IAAI,CAAC,GAAG,CAAC,CAAC;gBACZ,CAAC;YACH,CAAC,CAAC;YAED,MAAc,CAAC,MAAM,CAAC,CAAC,QAAQ,GAAG,IAAI,EAAE,GAAG,WAAW,EAAE,OAAO,CAAC,CAAC;QACpE,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/*\n * The MIT License\n *\n * Copyright (c) 2025 Catbee Technologies\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport type { RequestHandler, Router } from 'express';\nimport 'reflect-metadata';\nimport { HttpStatusCodes } from './http-status-codes';\nimport { ForbiddenException } from './exception.utils';\n\n// Metadata keys\nconst ROUTES_KEY = Symbol('routes');\nconst MIDDLEWARE_KEY = Symbol('middlewares');\nconst PARAMS_KEY = Symbol('params');\nconst HTTP_CODE_KEY = Symbol('httpCode');\nconst HEADER_KEY = Symbol('headers');\nconst BEFORE_KEY = Symbol('before');\nconst AFTER_KEY = Symbol('after');\nconst ROLES_KEY = Symbol('roles');\nconst REDIRECT_KEY = Symbol('redirect');\n\n/**\n * Supported HTTP methods for route decorators\n */\ntype HttpMethod = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options' | 'head' | 'trace' | 'connect';\n\n/**\n * Represents a route definition for controller methods\n */\ninterface RouteDefinition {\n /** The URL path for this route */\n path: string;\n /** HTTP method for this route */\n method: HttpMethod;\n /** Name of the handler method in the controller class */\n handlerName: string;\n}\n\n/**\n * Parameter decoration definition for method parameters\n */\ninterface ParamDefinition {\n /** Parameter position in method signature */\n index: number;\n /** Type of parameter (query, body, etc.) */\n type: 'query' | 'param' | 'body' | 'req' | 'res';\n /** Optional key for extracting specific property */\n key?: string;\n}\n\n/**\n * Factory function that creates HTTP method decorators.\n *\n * @param method - HTTP method to create decorator for\n * @returns A method decorator function\n */\nfunction createRouteDecorator(method: HttpMethod) {\n return (path: string): MethodDecorator => {\n return (target, propertyKey, descriptor) => {\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, target.constructor) || [];\n routes.push({\n path,\n method,\n handlerName: propertyKey as string\n });\n Reflect.defineMetadata(ROUTES_KEY, routes, target.constructor);\n };\n };\n}\n\n/**\n * Decorator for GET HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users')\n * getUsers() {\n * return this.userService.findAll();\n * }\n * ```\n */\nexport const Get = createRouteDecorator('get');\n\n/**\n * Decorator for POST HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * createUser(@Body() userData: any) {\n * return this.userService.create(userData);\n * }\n * ```\n */\nexport const Post = createRouteDecorator('post');\n\n/**\n * Decorator for PUT HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Put = createRouteDecorator('put');\n\n/**\n * Decorator for PATCH HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Patch = createRouteDecorator('patch');\n\n/**\n * Decorator for DELETE HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Delete = createRouteDecorator('delete');\n\n/**\n * Decorator for OPTIONS HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Options = createRouteDecorator('options');\n\n/**\n * Decorator for HEAD HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Head = createRouteDecorator('head');\n\n/**\n * Decorator for TRACE HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Trace = createRouteDecorator('trace');\n\n/**\n * Decorator for CONNECT HTTP method routes.\n *\n * @param path - URL path for the route\n * @returns Method decorator\n */\nexport const Connect = createRouteDecorator('connect');\n\n/**\n * Decorator that marks a class as a controller with a base path.\n * Used as the entry point for routing configuration.\n *\n * @param basePath - Base URL path for all routes in this controller\n * @returns Class decorator\n *\n * @example\n * ```ts\n * @Controller('/api/users')\n * class UserController {\n * // Controller methods...\n * }\n * ```\n */\nexport function Controller(basePath: string): ClassDecorator {\n return target => {\n Reflect.defineMetadata('basePath', basePath, target);\n };\n}\n\n/**\n * Decorator that applies middleware to a controller method.\n * Multiple middlewares can be applied and will execute in order.\n *\n * @param middlewares - Express middleware functions to apply\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/protected')\n * @Use(authMiddleware, loggingMiddleware)\n * getProtectedResource() {\n * // This route is protected by auth middleware\n * }\n * ```\n */\nexport function Use(...middlewares: RequestHandler[]): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const existing: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, target, propertyKey as string) || [];\n Reflect.defineMetadata(MIDDLEWARE_KEY, [...existing, ...middlewares], target, propertyKey as string);\n };\n}\n\n/**\n * Factory function that creates parameter decorators.\n *\n * @param type - Parameter type to extract from request\n * @param key - Optional fixed key for extraction\n * @returns Parameter decorator function\n */\nfunction createParamDecorator(type: ParamDefinition['type'], key?: string) {\n return (paramKey?: string): ParameterDecorator => {\n return (target, propertyKey, parameterIndex) => {\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, target, propertyKey as string) || [];\n // Ensure parameters are ordered by index\n params.push({ index: parameterIndex, type, key: paramKey || key });\n params.sort((a, b) => a.index - b.index);\n Reflect.defineMetadata(PARAMS_KEY, params, target, propertyKey as string);\n };\n };\n}\n\n/**\n * Decorator that extracts query parameters from request.\n *\n * @param paramKey - Optional key to extract specific query parameter\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/search')\n * search(@Query('term') searchTerm: string) {\n * // searchTerm will contain the value of req.query.term\n * }\n * ```\n */\nexport const Query = createParamDecorator('query');\n\n/**\n * Decorator that extracts route parameters from request.\n *\n * @param paramKey - Optional key to extract specific route parameter\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * getUser(@Param('id') userId: string) {\n * // userId will contain the value of req.params.id\n * }\n * ```\n */\nexport const Param = createParamDecorator('param');\n\n/**\n * Decorator that extracts body or body property from request.\n *\n * @param paramKey - Optional key to extract specific body property\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * createUser(@Body() userData: any) {\n * // userData will contain the entire req.body\n * }\n *\n * @Post('/update')\n * updateName(@Body('name') name: string) {\n * // name will contain the value of req.body.name\n * }\n * ```\n */\nexport const Body = createParamDecorator('body');\n\n/**\n * Decorator that injects the entire request object.\n *\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/complex')\n * complex(@Req() req: Request) {\n * // Access the full request object\n * console.log(req.headers);\n * }\n * ```\n */\nexport const Req = createParamDecorator('req');\n\n/**\n * Decorator that injects the response object.\n *\n * @returns Parameter decorator\n *\n * @example\n * ```ts\n * @Get('/custom')\n * custom(@Res() res: Response) {\n * // Direct access to response object\n * return res.status(201).send('Created');\n * }\n * ```\n */\nexport const Res = createParamDecorator('res');\n\n/**\n * Decorator that sets a custom HTTP status code for a response.\n *\n * @param status - HTTP status code to use\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Post('/users')\n * @HttpCode(201)\n * createUser(@Body() userData: any) {\n * // Response will have 201 Created status code\n * return { id: '123', ...userData };\n * }\n * ```\n */\nexport function HttpCode(status: number): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n Reflect.defineMetadata(HTTP_CODE_KEY, status, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that adds a custom HTTP header to the response.\n *\n * @param name - Header name\n * @param value - Header value\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/data')\n * @Header('Cache-Control', 'max-age=60')\n * getData() {\n * // Response will include the Cache-Control header\n * return { data: '...' };\n * }\n * ```\n */\nexport function Header(name: string, value: string): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, target, propertyKey as string) || {};\n headers[name] = value;\n Reflect.defineMetadata(HEADER_KEY, headers, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that registers a function to run before route handler execution.\n * Useful for pre-processing or logging.\n *\n * @param fn - Function to execute before the handler\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * @Before((req, res) => console.log(`Accessing user ${req.params.id}`))\n * getUser(@Param('id') id: string) {\n * // Function will log before this handler runs\n * }\n * ```\n */\nexport function Before(fn: Function): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(BEFORE_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(BEFORE_KEY, hooks, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that registers a function to run after route handler execution.\n * Can access the handler's result.\n *\n * @param fn - Function to execute after the handler\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/users/:id')\n * @After((req, res, result) => console.log(`User data sent: ${JSON.stringify(result)}`))\n * getUser(@Param('id') id: string) {\n * // After this handler, the function will log the returned data\n * return { id, name: 'Example' };\n * }\n * ```\n */\nexport function After(fn: Function): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n const hooks: Function[] = Reflect.getMetadata(AFTER_KEY, target, propertyKey as string) || [];\n hooks.push(fn);\n Reflect.defineMetadata(AFTER_KEY, hooks, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that requires specific roles for accessing a route.\n * Must be used with authentication middleware.\n *\n * @param roles - List of roles that can access this route\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/admin/settings')\n * @Roles('admin', 'superuser')\n * getSettings() {\n * // Only admins and superusers can access\n * return { settings: [...] };\n * }\n * ```\n */\nexport function Roles(...roles: string[]): MethodDecorator {\n return (target, propertyKey, _descriptor) => {\n Reflect.defineMetadata(ROLES_KEY, roles, target, propertyKey as string);\n };\n}\n\n/**\n * Decorator that redirects to another URL.\n *\n * @param url - URL to redirect to (can be absolute or relative)\n * @param statusCode - HTTP status code for redirect (default: 302)\n * @returns Method decorator\n *\n * @example\n * ```ts\n * @Get('/old-path')\n * @Redirect('/new-path', 301)\n * redirectToNewPath() {\n * // This method won't be executed; automatic redirect happens\n * }\n *\n * @Get('/dynamic-redirect')\n * @Redirect()\n * getDynamicRedirect() {\n * // Return an object with url and optionally statusCode\n * return { url: '/calculated-path', statusCode: 307 };\n * }\n * ```\n */\nexport function Redirect(url?: string, statusCode: number = 302): MethodDecorator {\n return (target, propertyKey, descriptor) => {\n // Store the redirect information in metadata\n Reflect.defineMetadata(REDIRECT_KEY, { url, statusCode }, target, propertyKey as string);\n return descriptor;\n };\n}\n\n/**\n * Registers all controller classes with the provided router.\n * This function processes all decorators and sets up the Express routes.\n *\n * @param router - Express router instance\n * @param controllers - Array of controller classes\n */\nexport function registerControllers(router: Router, controllers: any[]) {\n controllers.forEach(ControllerClass => {\n const instance = new ControllerClass();\n const basePath: string = Reflect.getMetadata('basePath', ControllerClass) || '';\n const routes: RouteDefinition[] = Reflect.getMetadata(ROUTES_KEY, ControllerClass) || [];\n\n routes.forEach(({ path, method, handlerName }) => {\n const middlewares: RequestHandler[] = Reflect.getMetadata(MIDDLEWARE_KEY, instance, handlerName) || [];\n const params: ParamDefinition[] = Reflect.getMetadata(PARAMS_KEY, instance, handlerName) || [];\n\n const httpCode: number | undefined = Reflect.getMetadata(HTTP_CODE_KEY, instance, handlerName);\n const headers: Record<string, string> = Reflect.getMetadata(HEADER_KEY, instance, handlerName) || {};\n const beforeHooks: Function[] = Reflect.getMetadata(BEFORE_KEY, instance, handlerName) || [];\n const afterHooks: Function[] = Reflect.getMetadata(AFTER_KEY, instance, handlerName) || [];\n const roles: string[] = Reflect.getMetadata(ROLES_KEY, instance, handlerName) || [];\n const redirect: { url?: string; statusCode: number } | undefined = Reflect.getMetadata(\n REDIRECT_KEY,\n instance,\n handlerName\n );\n\n const handler: RequestHandler = async (req, res, next) => {\n try {\n // Handle roles-based access control\n if (roles.length && !(req as any)?.user?.roles?.some((role: string) => roles.includes(role))) {\n res.status(HttpStatusCodes.FORBIDDEN).json(new ForbiddenException('Forbidden Insufficient Roles'));\n return;\n }\n\n // Process static redirect if configured\n if (redirect && redirect.url) {\n return res.redirect(redirect.statusCode, redirect.url);\n }\n\n for (const fn of beforeHooks) await fn(req, res);\n const args: any[] = [];\n if (params.length) {\n params.forEach(({ index, type, key }) => {\n switch (type) {\n case 'query':\n args[index] = key ? req.query[key] : req.query;\n break;\n case 'param':\n args[index] = key ? req.params[key] : req.params;\n break;\n case 'body':\n args[index] = key ? req.body?.[key] : req.body;\n break;\n case 'req':\n args[index] = req;\n break;\n case 'res':\n args[index] = res;\n break;\n }\n });\n }\n const result = (instance as any)[handlerName](...args);\n // Support both sync and async handlers\n const awaited = result instanceof Promise ? await result : result;\n\n // Handle dynamic redirects\n if (redirect && awaited && typeof awaited === 'object' && 'url' in awaited) {\n const redirectUrl = awaited.url as string;\n const redirectStatus = (awaited.statusCode as number) || redirect.statusCode;\n return res.redirect(redirectStatus, redirectUrl);\n }\n\n if (!res.headersSent && typeof awaited !== 'undefined') {\n if (httpCode) res.status?.(httpCode);\n for (const [k, v] of Object.entries(headers)) res.set?.(k, v);\n res.json(awaited);\n }\n for (const fn of afterHooks) await fn(req, res, awaited);\n } catch (err) {\n next(err);\n }\n };\n\n (router as any)[method](basePath + path, ...middlewares, handler);\n });\n });\n}\n"]}
@@ -1,3 +1,26 @@
1
+ /*
2
+ * The MIT License
3
+ *
4
+ * Copyright (c) 2025 Catbee Technologies
5
+ *
6
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ * of this software and associated documentation files (the "Software"), to deal
8
+ * in the Software without restriction, including without limitation the rights
9
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ * copies of the Software, and to permit persons to whom the Software is
11
+ * furnished to do so, subject to the following conditions:
12
+ *
13
+ * The above copyright notice and this permission notice shall be included in all
14
+ * copies or substantial portions of the Software.
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ * SOFTWARE.
23
+ */
1
24
  import os from 'os';
2
25
  import fs from 'fs';
3
26
  import fsp from 'fs/promises';