@vercube/core 0.0.1-alpha.15

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 (74) hide show
  1. package/dist/Common/App.d.ts +56 -0
  2. package/dist/Common/Container.d.ts +8 -0
  3. package/dist/Common/CreateApp.d.ts +8 -0
  4. package/dist/Config/Config.d.ts +7 -0
  5. package/dist/Config/DefaultConfig.d.ts +6 -0
  6. package/dist/Config/Loader.d.ts +7 -0
  7. package/dist/Decorators/Hooks/Listen.d.ts +9 -0
  8. package/dist/Decorators/Http/Body.d.ts +15 -0
  9. package/dist/Decorators/Http/Connect.d.ts +10 -0
  10. package/dist/Decorators/Http/Controller.d.ts +10 -0
  11. package/dist/Decorators/Http/Delete.d.ts +10 -0
  12. package/dist/Decorators/Http/Get.d.ts +10 -0
  13. package/dist/Decorators/Http/Head.d.ts +10 -0
  14. package/dist/Decorators/Http/Header.d.ts +11 -0
  15. package/dist/Decorators/Http/Headers.d.ts +9 -0
  16. package/dist/Decorators/Http/Middleware.d.ts +27 -0
  17. package/dist/Decorators/Http/MultipartFormData.d.ts +15 -0
  18. package/dist/Decorators/Http/Options.d.ts +10 -0
  19. package/dist/Decorators/Http/Param.d.ts +12 -0
  20. package/dist/Decorators/Http/Patch.d.ts +10 -0
  21. package/dist/Decorators/Http/Post.d.ts +10 -0
  22. package/dist/Decorators/Http/Put.d.ts +10 -0
  23. package/dist/Decorators/Http/QueryParam.d.ts +16 -0
  24. package/dist/Decorators/Http/QueryParams.d.ts +15 -0
  25. package/dist/Decorators/Http/Redirect.d.ts +13 -0
  26. package/dist/Decorators/Http/Request.d.ts +9 -0
  27. package/dist/Decorators/Http/Response.d.ts +9 -0
  28. package/dist/Decorators/Http/Session.d.ts +9 -0
  29. package/dist/Decorators/Http/SetHeader.d.ts +7 -0
  30. package/dist/Decorators/Http/Status.d.ts +11 -0
  31. package/dist/Decorators/Http/Trace.d.ts +10 -0
  32. package/dist/Errors/Http/BadRequestError.d.ts +17 -0
  33. package/dist/Errors/Http/ForbiddenError.d.ts +17 -0
  34. package/dist/Errors/Http/InternalServerError.d.ts +17 -0
  35. package/dist/Errors/Http/MethodNotAllowedError.d.ts +17 -0
  36. package/dist/Errors/Http/NotAcceptableError.d.ts +17 -0
  37. package/dist/Errors/Http/NotFoundError.d.ts +17 -0
  38. package/dist/Errors/Http/UnauthorizedError.d.ts +17 -0
  39. package/dist/Errors/HttpError.d.ts +17 -0
  40. package/dist/Hooks/Router/RouterAfterInitHook.d.ts +1 -0
  41. package/dist/Hooks/Router/RouterBeforeInitHook.d.ts +1 -0
  42. package/dist/Middleware/ValidationMiddleware.d.ts +23 -0
  43. package/dist/Resolvers/Body.d.ts +22 -0
  44. package/dist/Resolvers/Headers.d.ts +14 -0
  45. package/dist/Resolvers/Query.d.ts +14 -0
  46. package/dist/Resolvers/RouterParam.d.ts +13 -0
  47. package/dist/Services/Config/RuntimeConfig.d.ts +22 -0
  48. package/dist/Services/ErrorHandler/DefaultErrorHandlerProvider.d.ts +16 -0
  49. package/dist/Services/ErrorHandler/ErrorHandlerProvider.d.ts +16 -0
  50. package/dist/Services/Hooks/HooksService.d.ts +76 -0
  51. package/dist/Services/HttpServer/HttpServer.d.ts +51 -0
  52. package/dist/Services/Metadata/MetadataResolver.d.ts +42 -0
  53. package/dist/Services/Middleware/BaseMiddleware.d.ts +31 -0
  54. package/dist/Services/Middleware/GlobalMiddlewareRegistry.d.ts +31 -0
  55. package/dist/Services/Plugins/BasePlugin.d.ts +16 -0
  56. package/dist/Services/Plugins/PluginsRegistry.d.ts +26 -0
  57. package/dist/Services/Router/RequestHandler.d.ts +65 -0
  58. package/dist/Services/Router/Router.d.ts +40 -0
  59. package/dist/Services/Router/StaticRequestHandler.d.ts +38 -0
  60. package/dist/Services/Validation/StandardSchemaValidationProvider.d.ts +17 -0
  61. package/dist/Services/Validation/ValidationProvider.d.ts +17 -0
  62. package/dist/Types/CommonTypes.d.ts +6 -0
  63. package/dist/Types/ConfigTypes.d.ts +120 -0
  64. package/dist/Types/HooksTypes.d.ts +17 -0
  65. package/dist/Types/HttpTypes.d.ts +63 -0
  66. package/dist/Types/MetadataTypes.d.ts +54 -0
  67. package/dist/Types/ValidationTypes.d.ts +6 -0
  68. package/dist/Utils/InternalUtils.d.ts +5 -0
  69. package/dist/Utils/Mine.d.ts +3 -0
  70. package/dist/Utils/Utils.d.ts +22 -0
  71. package/dist/index.cjs +2018 -0
  72. package/dist/index.d.ts +46 -0
  73. package/dist/index.mjs +1944 -0
  74. package/package.json +35 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,2018 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod) => function() {
9
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
13
+ key = keys[i];
14
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
15
+ get: ((k) => from[k]).bind(null, key),
16
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
17
+ });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
22
+ value: mod,
23
+ enumerable: true
24
+ }) : target, mod));
25
+
26
+ //#endregion
27
+ const __vercube_di = __toESM(require("@vercube/di"));
28
+ const srvx = __toESM(require("srvx"));
29
+ const rou3 = __toESM(require("rou3"));
30
+ const node_fs = __toESM(require("node:fs"));
31
+ const node_path = __toESM(require("node:path"));
32
+ const node_fs_promises = __toESM(require("node:fs/promises"));
33
+ const __vercube_logger = __toESM(require("@vercube/logger"));
34
+ const c12 = __toESM(require("c12"));
35
+ const defu = __toESM(require("defu"));
36
+
37
+ //#region node_modules/.pnpm/@oxc-project+runtime@0.62.0/node_modules/@oxc-project/runtime/src/helpers/decorate.js
38
+ var require_decorate = __commonJS({ "node_modules/.pnpm/@oxc-project+runtime@0.62.0/node_modules/@oxc-project/runtime/src/helpers/decorate.js"(exports, module) {
39
+ function __decorate(decorators, target, key, desc) {
40
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
41
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
42
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
43
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
44
+ }
45
+ module.exports = __decorate, module.exports.__esModule = true, module.exports["default"] = module.exports;
46
+ } });
47
+ var import_decorate = __toESM(require_decorate(), 1);
48
+
49
+ //#endregion
50
+ //#region packages/core/src/Services/Plugins/PluginsRegistry.ts
51
+ var PluginsRegistry = class {
52
+ gContainer;
53
+ /** Holds the list of plugins */
54
+ fPlugins = new Map();
55
+ /**
56
+ * Registers a plugin.
57
+ *
58
+ * @param {Plugin} plugin - The plugin to register.
59
+ * @param {unknown} options - The options to pass to the plugin.
60
+ */
61
+ register(plugin, options) {
62
+ const instance = this.gContainer.resolve(plugin);
63
+ this.fPlugins.set(instance.name, {
64
+ instance,
65
+ options
66
+ });
67
+ }
68
+ /**
69
+ * Gets the list of registered plugins.
70
+ *
71
+ * @returns {Plugin[]} The list of registered plugins.
72
+ */
73
+ get plugins() {
74
+ return [...this.fPlugins.values()].map((plugin) => plugin.instance);
75
+ }
76
+ /**
77
+ * Resolves the plugins.
78
+ *
79
+ * @param {App} app - The application instance.
80
+ */
81
+ async init(app) {
82
+ for (const { instance, options } of this.fPlugins.values()) await instance.use(app, options);
83
+ }
84
+ };
85
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(__vercube_di.Container)], PluginsRegistry.prototype, "gContainer", void 0);
86
+
87
+ //#endregion
88
+ //#region packages/core/src/Services/Hooks/HooksService.ts
89
+ var HooksService = class {
90
+ fLastId = 0;
91
+ fHandlers = new Map();
92
+ /**
93
+ * Registers listener for event of particular type. Everytime event is called, the listener
94
+ * will be executed.
95
+ *
96
+ * @param type type of event, simple class
97
+ * @param callback callback fired when event is triggered
98
+ * @returns unique ID for event listener, can be used to disable this listener
99
+ */
100
+ on(type, callback) {
101
+ let handlersOfType = this.fHandlers.get(type);
102
+ if (!handlersOfType) {
103
+ handlersOfType = [];
104
+ this.fHandlers.set(type, handlersOfType);
105
+ }
106
+ const genId = this.fLastId++;
107
+ const handler = {
108
+ callback,
109
+ id: genId
110
+ };
111
+ handlersOfType.push(handler);
112
+ return {
113
+ __id: genId,
114
+ __type: type
115
+ };
116
+ }
117
+ /**
118
+ * Waits for single event execution and removes the listener immediately after.
119
+ *
120
+ * @example
121
+ * this.gCart.addItem(product);
122
+ * await this.gEvents.waitFor(CartUpdatedEvent);
123
+ * console.log('here cart updated event is already called');
124
+ *
125
+ * @param type type of event to wait for
126
+ * @param timeout timeout param in ms - if event is not thrown until this time, it'll reject. passing null disables the timeout
127
+ * @returns promise with event data that resolves when event is finally called
128
+ */
129
+ waitFor(type, timeout = 10 * 1e3) {
130
+ return new Promise((resolve, reject) => {
131
+ let waitTimeout;
132
+ const eventId = this.on(type, (data) => {
133
+ this.off(eventId);
134
+ resolve(data);
135
+ if (waitTimeout) clearTimeout(waitTimeout);
136
+ });
137
+ if (timeout !== null) waitTimeout = setTimeout(() => {
138
+ this.off(eventId);
139
+ reject(new Error(`Waiting for event timeout - ${type.name}`));
140
+ }, timeout);
141
+ });
142
+ }
143
+ /**
144
+ * Removes listener from particular event.
145
+ * @param eventId eventId returned from .on() method.
146
+ * @throws Error if event was not registered
147
+ */
148
+ off(eventId) {
149
+ const type = eventId.__type;
150
+ const handlersOfType = this.fHandlers.get(type);
151
+ if (!handlersOfType) throw new Error("Trying to unbind event that was not bound.");
152
+ const index = handlersOfType.findIndex((handler) => handler.id === eventId.__id);
153
+ if (index === -1) throw new Error("Trying to unbind event that was not bound.");
154
+ handlersOfType.splice(index, 1);
155
+ }
156
+ /**
157
+ * Triggers event, calling all listener callbacks. Will return Promise of number,
158
+ * that is resolved when all asynchronous listeners are called.
159
+ * @param type type of trigger, simple class
160
+ * @param data data which will be passed to listeners, based on event class
161
+ * @return number of listeners that were notified
162
+ */
163
+ async trigger(type, data) {
164
+ const handlersOfType = this.fHandlers.get(type);
165
+ if (!handlersOfType) return 0;
166
+ const toProcessHandlers = [...handlersOfType];
167
+ const promises = toProcessHandlers.map((handler) => {
168
+ const instance = this.objectToClass(type, data);
169
+ const result = handler.callback(instance);
170
+ return result instanceof Promise ? result : Promise.resolve();
171
+ });
172
+ await Promise.all(promises);
173
+ return toProcessHandlers.length;
174
+ }
175
+ /**
176
+ * Converts plain object to it's class equivalent.
177
+ * It's NOT class-transformer, it performs basic key assigment.
178
+ *
179
+ * @param ClassConstructor event constructor
180
+ * @param data event data to be mapped to constructor
181
+ * @return class type of event
182
+ */
183
+ objectToClass(ClassConstructor, data) {
184
+ const instance = new ClassConstructor();
185
+ if (data) for (const key of Object.keys(data)) {
186
+ const rawInstance = instance;
187
+ const rawData = data;
188
+ rawInstance[key] = rawData[key];
189
+ }
190
+ return instance;
191
+ }
192
+ };
193
+
194
+ //#endregion
195
+ //#region packages/core/src/Hooks/Router/RouterBeforeInitHook.ts
196
+ var RouterBeforeInitHook = class {};
197
+
198
+ //#endregion
199
+ //#region packages/core/src/Hooks/Router/RouterAfterInitHook.ts
200
+ var RouterAfterInitHook = class {};
201
+
202
+ //#endregion
203
+ //#region packages/core/src/Services/Router/Router.ts
204
+ var Router = class {
205
+ /**
206
+ * Service for triggering application hooks
207
+ */
208
+ gHooksService;
209
+ /**
210
+ * Internal router context that stores all registered routes
211
+ * @private
212
+ */
213
+ fRouterContext;
214
+ /**
215
+ * Registers a new route in the router
216
+ *
217
+ * @param {RouterTypes.Route} route - The route configuration to add
218
+ * @throws {Error} If router is not initialized
219
+ */
220
+ addRoute(route) {
221
+ if (!this.fRouterContext) throw new Error("Router not initialized. Please call init() before adding routes.");
222
+ (0, rou3.addRoute)(this.fRouterContext, route.method.toUpperCase(), route.path, route.handler);
223
+ }
224
+ /**
225
+ * Initializes the router and triggers related hooks
226
+ *
227
+ * This method creates a new router context and triggers
228
+ * the before and after initialization hooks.
229
+ */
230
+ init() {
231
+ this.gHooksService.trigger(RouterBeforeInitHook);
232
+ this.fRouterContext = (0, rou3.createRouter)();
233
+ this.gHooksService.trigger(RouterAfterInitHook);
234
+ }
235
+ /**
236
+ * Resolves a route based on the HTTP method and path
237
+ *
238
+ * @param {RouterTypes.RouteFind} route - The route to resolve
239
+ * @returns {RouterTypes.RouteMatched<RouterTypes.RouterHandler> | undefined} The matched route or undefined if no match found
240
+ */
241
+ resolve(route) {
242
+ let url = route.path;
243
+ try {
244
+ url = new URL(route.path).pathname;
245
+ } catch {}
246
+ return (0, rou3.findRoute)(this.fRouterContext, route.method.toUpperCase(), url);
247
+ }
248
+ };
249
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(HooksService)], Router.prototype, "gHooksService", void 0);
250
+
251
+ //#endregion
252
+ //#region packages/core/src/Resolvers/RouterParam.ts
253
+ function resolveRouterParam(param, event) {
254
+ return event.params?.[param] ?? null;
255
+ }
256
+
257
+ //#endregion
258
+ //#region packages/core/src/Errors/HttpError.ts
259
+ var HttpError = class HttpError extends Error {
260
+ /**
261
+ * The HTTP status code associated with the error.
262
+ * @type {number}
263
+ */
264
+ status;
265
+ /**
266
+ * Creates an instance of HttpError.
267
+ * @param {number} status - The HTTP status code.
268
+ * @param {string} [message] - The error message.
269
+ */
270
+ constructor(status, message) {
271
+ super();
272
+ Object.setPrototypeOf(this, HttpError.prototype);
273
+ if (status) this.status = status;
274
+ if (message) this.message = message;
275
+ this.stack = new Error().stack;
276
+ }
277
+ };
278
+
279
+ //#endregion
280
+ //#region packages/core/src/Errors/Http/BadRequestError.ts
281
+ var BadRequestError = class BadRequestError extends HttpError {
282
+ /**
283
+ * The name of the error.
284
+ * @type {string}
285
+ */
286
+ name = "BadRequestError";
287
+ /**
288
+ * Creates an instance of BadRequestError.
289
+ * @param {string} [message] - The error message.
290
+ */
291
+ constructor(message, errors) {
292
+ super(400);
293
+ Object.setPrototypeOf(this, BadRequestError.prototype);
294
+ if (message) this.message = message;
295
+ if (errors) this.errors = errors;
296
+ }
297
+ };
298
+
299
+ //#endregion
300
+ //#region packages/core/src/Resolvers/Body.ts
301
+ async function resolveRequestBody(event) {
302
+ const text = await event.request.text();
303
+ if (!text) return void 0;
304
+ try {
305
+ return JSON.parse(text);
306
+ } catch {
307
+ throw new BadRequestError("Invalid JSON body");
308
+ }
309
+ }
310
+
311
+ //#endregion
312
+ //#region packages/core/src/Resolvers/Query.ts
313
+ function resolveQueryParam(name, event) {
314
+ const url = new URL(event.request.url);
315
+ return url.searchParams.get(name);
316
+ }
317
+ function resolveQueryParams(event) {
318
+ const url = new URL(event.request.url);
319
+ const params = {};
320
+ for (const [key, value] of url.searchParams) params[key] = value;
321
+ return params;
322
+ }
323
+
324
+ //#endregion
325
+ //#region packages/core/src/Resolvers/Headers.ts
326
+ function getRequestHeader(header, event) {
327
+ return event.request.headers.get(header);
328
+ }
329
+ function getRequestHeaders(event) {
330
+ return event.request.headers;
331
+ }
332
+
333
+ //#endregion
334
+ //#region packages/core/src/Services/Metadata/MetadataResolver.ts
335
+ var MetadataResolver = class {
336
+ /**
337
+ * Resolves the URL for a given instance and path.
338
+ *
339
+ * @param {MetadataTypes.ResolveUrlParams} params - The parameters for resolving the URL.
340
+ * @return {string} The resolved URL.
341
+ */
342
+ resolveUrl(params) {
343
+ const { instance, propertyName, path: rawPath } = params;
344
+ const metadata = instance.__metadata;
345
+ const basePath = (metadata?.__controller?.path ?? "").replace(/\/$/, "");
346
+ const cleanPath = rawPath.replace(/^\//, "");
347
+ const url = `${basePath}/${cleanPath}`;
348
+ metadata.__methods[propertyName].url = url;
349
+ return url;
350
+ }
351
+ resolveMethod(ctx, propertyName) {
352
+ return ctx.__metadata.__methods[propertyName];
353
+ }
354
+ /**
355
+ * Resolves arguments for a given event.
356
+ *
357
+ * @param {MetadataTypes.Arg[]} args - The arguments to resolve.
358
+ * @param {RouterTypes.RouterEvent} event - The event to resolve arguments for.
359
+ * @return {unknown[]} The resolved arguments.
360
+ * @public
361
+ */
362
+ async resolveArgs(args, event) {
363
+ args.sort((a, b) => a.idx - b.idx);
364
+ const resolvedArgs = args.map(async (arg) => ({
365
+ ...arg,
366
+ resolved: await this.resolveArg(arg, event)
367
+ }));
368
+ return await Promise.all(resolvedArgs);
369
+ }
370
+ /**
371
+ * Resolves an argument for a given event.
372
+ *
373
+ * @param {MetadataTypes.Arg} arg - The argument to resolve.
374
+ *
375
+ * @return {unknown} The resolved argument.
376
+ * @private
377
+ */
378
+ resolveArg(arg, event) {
379
+ switch (arg.type) {
380
+ case "param": return resolveRouterParam(arg?.data?.name ?? "", event);
381
+ case "body": return resolveRequestBody(event);
382
+ case "multipart-form-data": return null;
383
+ case "query-param": return resolveQueryParam(arg?.data?.name ?? "", event);
384
+ case "query-params": return resolveQueryParams(event);
385
+ case "header": return getRequestHeader(arg.data?.name ?? "", event);
386
+ case "headers": return getRequestHeaders(event);
387
+ case "request": return event.request;
388
+ case "response": return event.response;
389
+ case "session": return null;
390
+ default: throw new Error(`Unknown argument type: ${arg.type}`);
391
+ }
392
+ }
393
+ /**
394
+ * Resolves middleware functions for a given context and property name.
395
+ *
396
+ * @param {MetadataTypes.Ctx} ctx - The metadata context object
397
+ * @param {string} propertyName - The name of the property to resolve middlewares for
398
+ * @returns {MetadataTypes.Middleware[]} Array of middleware functions that apply globally or to the specific property
399
+ * @public
400
+ */
401
+ resolveMiddlewares(ctx, propertyName) {
402
+ const middlewares = ctx?.__metadata?.__middlewares?.filter((m) => m.target === "__global__" || m.target === propertyName) ?? [];
403
+ return middlewares.sort((a) => a.target === "__global__" ? -1 : 1);
404
+ }
405
+ };
406
+
407
+ //#endregion
408
+ //#region packages/core/src/Services/ErrorHandler/ErrorHandlerProvider.ts
409
+ var ErrorHandlerProvider = class {};
410
+
411
+ //#endregion
412
+ //#region packages/core/src/Services/Middleware/GlobalMiddlewareRegistry.ts
413
+ var GlobalMiddlewareRegistry = class {
414
+ fMiddlewares = new Set();
415
+ /**
416
+ * Retrieves all registered global middleware configurations
417
+ *
418
+ * @returns {MetadataTypes.Middleware[]} An array of middleware configurations
419
+ */
420
+ get middlewares() {
421
+ return [...this.fMiddlewares.values()].map((m) => ({
422
+ ...m.opts,
423
+ target: "__global__",
424
+ middleware: m.middleware
425
+ }));
426
+ }
427
+ /**
428
+ * Registers a global middleware configuration
429
+ *
430
+ * @param {typeof BaseMiddleware<T, U>} middleware - The middleware class to register
431
+ * @param {GlobalMiddlewareParams<T>} opts - The middleware options
432
+ * @returns {void}
433
+ */
434
+ registerGlobalMiddleware(middleware, opts) {
435
+ this.fMiddlewares.add({
436
+ middleware,
437
+ opts
438
+ });
439
+ }
440
+ };
441
+
442
+ //#endregion
443
+ //#region packages/core/src/Services/Router/RequestHandler.ts
444
+ var RequestHandler = class {
445
+ /** Resolver for extracting metadata from controller classes and methods */
446
+ gMetadataResolver;
447
+ /** DI container for resolving dependencies */
448
+ gContainer;
449
+ /** Provider for handling errors during request processing */
450
+ gErrorHandlerProvider;
451
+ gGlobalMiddlewareRegistry;
452
+ /**
453
+ * Prepares a route handler by resolving its metadata and middlewares
454
+ *
455
+ * @param {RequestHandlerOptions} params - Configuration options for the handler
456
+ * @returns {RouterTypes.RouterHandler} A prepared handler with resolved metadata and middlewares
457
+ */
458
+ prepareHandler(params) {
459
+ const { instance, propertyName } = params;
460
+ const prototype = Object.getPrototypeOf(instance);
461
+ const method = this.gMetadataResolver.resolveMethod(prototype, propertyName);
462
+ const middlewares = this.gMetadataResolver.resolveMiddlewares(prototype, propertyName);
463
+ const globalMiddlewares = this.gGlobalMiddlewareRegistry.middlewares;
464
+ const uniqueMiddlewares = [...middlewares, ...globalMiddlewares].filter((m, index, self) => self.findIndex((t) => t.middleware === m.middleware) === index);
465
+ const resolvedMiddlewares = uniqueMiddlewares.map((m) => ({
466
+ ...m,
467
+ middleware: this.gContainer.resolve(m.middleware)
468
+ }));
469
+ const beforeMiddlewares = resolvedMiddlewares.filter((m) => !!m.middleware.onRequest);
470
+ const afterMiddlewares = resolvedMiddlewares.filter((m) => !!m.middleware.onResponse);
471
+ beforeMiddlewares.sort((a, b) => (a?.priority ?? 999) - (b?.priority ?? 999));
472
+ afterMiddlewares.sort((a, b) => (a?.priority ?? 999) - (b?.priority ?? 999));
473
+ return {
474
+ instance,
475
+ propertyName,
476
+ args: method.args,
477
+ middlewares: {
478
+ beforeMiddlewares,
479
+ afterMiddlewares
480
+ },
481
+ actions: method.actions
482
+ };
483
+ }
484
+ /**
485
+ * Processes an HTTP request through the middleware chain and route handler
486
+ *
487
+ * The request handling lifecycle:
488
+ * 1. Execute "before" middlewares
489
+ * 2. Apply route actions (status codes, redirects, etc.)
490
+ * 3. Resolve handler arguments
491
+ * 4. Execute the route handler
492
+ * 5. Execute "after" middlewares
493
+ * 6. Format and return the final response
494
+ *
495
+ * @param {Request} request - The incoming HTTP request
496
+ * @param {RouterTypes.RouteMatched<RouterTypes.RouterHandler>} route - The matched route with handler data
497
+ * @returns {Promise<Response>} The HTTP response
498
+ */
499
+ async handleRequest(request, route) {
500
+ try {
501
+ const { instance, propertyName, actions, args, middlewares } = route.data;
502
+ let fakeResponse = new Response(void 0, { headers: { "Content-Type": request.headers.get("Content-Type") ?? "application/json" } });
503
+ for await (const hook of middlewares?.beforeMiddlewares ?? []) try {
504
+ const hookResponse = await hook.middleware.onRequest?.(request, fakeResponse, {
505
+ middlewareArgs: hook.args,
506
+ methodArgs: args
507
+ });
508
+ if (hookResponse instanceof Response) return hookResponse;
509
+ } catch (error) {
510
+ return this.gErrorHandlerProvider.handleError(error);
511
+ }
512
+ for (const action of actions) {
513
+ const actionResponse = action.handler(request, fakeResponse);
514
+ if (actionResponse !== null) fakeResponse = this.processOverrideResponse(actionResponse, fakeResponse);
515
+ }
516
+ const resolvedArgs = await this.gMetadataResolver.resolveArgs(args, {
517
+ ...route,
518
+ request,
519
+ response: fakeResponse
520
+ });
521
+ let handlerResponse = instance[propertyName].call(instance, ...resolvedArgs?.map((a) => a.resolved) ?? []);
522
+ if (handlerResponse instanceof Promise) handlerResponse = await handlerResponse;
523
+ for await (const hook of middlewares?.afterMiddlewares ?? []) try {
524
+ const hookResponse = await hook.middleware.onResponse?.(request, fakeResponse, handlerResponse);
525
+ if (hookResponse !== null) fakeResponse = this.processOverrideResponse(hookResponse, fakeResponse);
526
+ } catch (error) {
527
+ return this.gErrorHandlerProvider.handleError(error);
528
+ }
529
+ const body = fakeResponse?.body ?? JSON.stringify(handlerResponse);
530
+ return new Response(body, {
531
+ status: fakeResponse.status,
532
+ statusText: fakeResponse.statusText,
533
+ headers: fakeResponse.headers
534
+ });
535
+ } catch (error_) {
536
+ return this.gErrorHandlerProvider.handleError(error_);
537
+ }
538
+ }
539
+ /**
540
+ * Processes and merges response overrides from middlewares or actions
541
+ *
542
+ * This method handles different response formats:
543
+ * - If a full Response object is provided, it's used directly
544
+ * - If ResponseInit is provided, it's merged with the base response
545
+ *
546
+ * @param {Response | ResponseInit} response - The response or response options to apply
547
+ * @param {Response} [base] - The base response to extend (optional)
548
+ * @returns {Response} The processed response with applied overrides
549
+ * @private
550
+ */
551
+ processOverrideResponse(response, base) {
552
+ let fakeResponse = base ?? new Response();
553
+ if (response != null && response instanceof Response) return response;
554
+ else if (response !== null) {
555
+ const responseInit = response;
556
+ fakeResponse = new Response(void 0, {
557
+ status: responseInit?.status ?? fakeResponse.status,
558
+ headers: responseInit?.headers ?? fakeResponse.headers,
559
+ statusText: responseInit?.statusText ?? fakeResponse.statusText
560
+ });
561
+ }
562
+ return fakeResponse;
563
+ }
564
+ };
565
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], RequestHandler.prototype, "gMetadataResolver", void 0);
566
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(__vercube_di.Container)], RequestHandler.prototype, "gContainer", void 0);
567
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(ErrorHandlerProvider)], RequestHandler.prototype, "gErrorHandlerProvider", void 0);
568
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(GlobalMiddlewareRegistry)], RequestHandler.prototype, "gGlobalMiddlewareRegistry", void 0);
569
+
570
+ //#endregion
571
+ //#region packages/core/src/Utils/Mine.ts
572
+ const mime = { getType(ext) {
573
+ const types = {
574
+ ".html": "text/html",
575
+ ".css": "text/css",
576
+ ".js": "application/javascript",
577
+ ".json": "application/json",
578
+ ".png": "image/png",
579
+ ".jpg": "image/jpeg",
580
+ ".jpeg": "image/jpeg",
581
+ ".gif": "image/gif",
582
+ ".svg": "image/svg+xml",
583
+ ".ico": "image/x-icon"
584
+ };
585
+ return types[ext] || null;
586
+ } };
587
+
588
+ //#endregion
589
+ //#region packages/core/src/Services/Router/StaticRequestHandler.ts
590
+ var StaticRequestHandler = class {
591
+ /**
592
+ * The options for the static server
593
+ */
594
+ fOptions;
595
+ /**
596
+ * Initializes the static server with the given options
597
+ *
598
+ * @param {ConfigTypes.ServerOptions['static']} options - The options for the static server
599
+ * @returns {void}
600
+ */
601
+ initialize(options) {
602
+ this.fOptions = options;
603
+ }
604
+ /**
605
+ * Handles HTTP requests for static files
606
+ *
607
+ * @param {Request} request - The incoming HTTP request
608
+ * @returns {Promise<void | Response>} A promise that resolves to void or a Response object
609
+ */
610
+ async handleRequest(request) {
611
+ const dirs = this.fOptions?.dirs ?? [];
612
+ if (!dirs) return;
613
+ if (request.method !== "GET") return;
614
+ const url = new URL(request.url);
615
+ const path = (0, node_path.normalize)(url.pathname);
616
+ let relativePath = path;
617
+ for (const dir of dirs) relativePath = relativePath.replace(dir, "");
618
+ for (const dir of dirs) {
619
+ const fullPath = (0, node_path.join)(process.cwd(), dir, relativePath);
620
+ try {
621
+ const stats = await (0, node_fs_promises.stat)(fullPath);
622
+ if (stats.isDirectory()) continue;
623
+ if (stats.isFile()) return this.serveFile(fullPath, stats);
624
+ } catch {
625
+ continue;
626
+ }
627
+ }
628
+ }
629
+ /**
630
+ * Serves a static file and returns a Response object
631
+ *
632
+ * @param {string} path - The path to the file to serve
633
+ * @param {any} stats - The stats object for the file
634
+ * @returns {Promise<Response>} A promise that resolves to a Response object
635
+ */
636
+ async serveFile(path, stats) {
637
+ const headers = new Headers();
638
+ const ext = (0, node_path.extname)(path).toLowerCase();
639
+ const contentType = mime.getType(ext) || "application/octet-stream";
640
+ headers.set("Content-Type", contentType);
641
+ headers.set("Content-Length", stats.size.toString());
642
+ if (this.fOptions?.maxAge && this.fOptions.maxAge > 0) {
643
+ const directives = ["public", `max-age=${this.fOptions.maxAge}`];
644
+ if (this.fOptions?.immutable) directives.push("immutable");
645
+ headers.set("Cache-Control", directives.join(", "));
646
+ }
647
+ if (this.fOptions?.etag) headers.set("ETag", `W/"${stats.size}-${stats.mtime.getTime()}"`);
648
+ const stream = (0, node_fs.createReadStream)(path);
649
+ return new Response(stream, { headers });
650
+ }
651
+ };
652
+
653
+ //#endregion
654
+ //#region packages/core/src/Services/HttpServer/HttpServer.ts
655
+ var HttpServer = class {
656
+ /**
657
+ * Router service for resolving routes
658
+ */
659
+ gRouter;
660
+ /**
661
+ * Handler for processing HTTP requests
662
+ */
663
+ gRequestHandler;
664
+ /**
665
+ * Error handler provider for managing error responses
666
+ */
667
+ gErrorHandlerProvider;
668
+ /**
669
+ * Static server for serving static files
670
+ */
671
+ gStaticRequestHandler;
672
+ /**
673
+ * Underlying server instance
674
+ * @private
675
+ */
676
+ fServer;
677
+ /**
678
+ * Initializes the HTTP server and starts listening for requests
679
+ *
680
+ * @returns {Promise<void>} A promise that resolves when the server is ready
681
+ */
682
+ async initialize(config) {
683
+ const { port, host } = config.server ?? {};
684
+ this.fServer = (0, srvx.serve)({
685
+ bun: { error: (error) => {
686
+ return this.gErrorHandlerProvider.handleError(error);
687
+ } },
688
+ deno: { onError: (error) => {
689
+ return this.gErrorHandlerProvider.handleError(error);
690
+ } },
691
+ hostname: host,
692
+ port,
693
+ fetch: this.handleRequest.bind(this)
694
+ });
695
+ await this.fServer.ready();
696
+ }
697
+ /**
698
+ * Processes an incoming HTTP request
699
+ *
700
+ * This method:
701
+ * 1. Resolves the route for the request
702
+ * 2. Returns a 404 response if no route is found
703
+ * 3. Delegates to the request handler for matched routes
704
+ *
705
+ * @param {Request} request - The incoming HTTP request
706
+ * @returns {Promise<Response>} The HTTP response
707
+ * @private
708
+ */
709
+ async handleRequest(request) {
710
+ try {
711
+ const route = this.gRouter.resolve({
712
+ path: request.url,
713
+ method: request.method
714
+ });
715
+ if (!route) {
716
+ const response = await this.gStaticRequestHandler.handleRequest(request);
717
+ if (response) return response;
718
+ else throw new NotFoundError("Route not found");
719
+ }
720
+ return this.gRequestHandler.handleRequest(request, route);
721
+ } catch (error) {
722
+ return this.gErrorHandlerProvider.handleError(error);
723
+ }
724
+ }
725
+ };
726
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], HttpServer.prototype, "gRouter", void 0);
727
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], HttpServer.prototype, "gRequestHandler", void 0);
728
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(ErrorHandlerProvider)], HttpServer.prototype, "gErrorHandlerProvider", void 0);
729
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(StaticRequestHandler)], HttpServer.prototype, "gStaticRequestHandler", void 0);
730
+
731
+ //#endregion
732
+ //#region packages/core/src/Common/App.ts
733
+ var App = class {
734
+ gRouter;
735
+ gPluginsRegistry;
736
+ gHttpServer;
737
+ gStaticRequestHandler;
738
+ /** Holds the initialization status of the application */
739
+ fIsInitialized = false;
740
+ /** Holds the dependency injection container */
741
+ fInternalContainer;
742
+ /** Hold app config */
743
+ fConfig;
744
+ /**
745
+ * Gets the dependency injection container.
746
+ *
747
+ * @returns {Container} The dependency injection container.
748
+ */
749
+ get container() {
750
+ return this.fInternalContainer;
751
+ }
752
+ /**
753
+ * Sets the dependency injection container.
754
+ *
755
+ * @param {Container} container - The dependency injection container.
756
+ */
757
+ set container(container) {
758
+ this.fInternalContainer = container;
759
+ }
760
+ /**
761
+ * Initializes the application.
762
+ *
763
+ * @returns {Promise<void>} A promise that resolves when the application is initialized.
764
+ */
765
+ async init(cfg) {
766
+ this.fConfig = cfg;
767
+ await this.gHttpServer.initialize(this.fConfig);
768
+ if (this.fConfig.server?.static) this.gStaticRequestHandler.initialize(this.fConfig.server?.static);
769
+ this.gRouter.init();
770
+ }
771
+ /**
772
+ * Registers a plugin.
773
+ *
774
+ * @param {typeof Plugin} plugin - The plugin to register.
775
+ * @param {unknown} options - The options to pass to the plugin.
776
+ */
777
+ registerPlugin(plugin, options) {
778
+ this.gPluginsRegistry.register(plugin, options);
779
+ }
780
+ /**
781
+ * Starts the application and begins listening for incoming requests.
782
+ *
783
+ * @returns {Promise<void>} A promise that resolves when the application starts listening.
784
+ * @throws {Error} If the application is already initialized.
785
+ */
786
+ async listen() {
787
+ if (this.fIsInitialized) throw new Error("App is already initialized");
788
+ await this.resolvePlugins();
789
+ (0, __vercube_di.initializeContainer)(this.container);
790
+ }
791
+ /**
792
+ * Resolves and initializes the plugins for the application.
793
+ *
794
+ * @private
795
+ */
796
+ async resolvePlugins() {
797
+ await this.gPluginsRegistry.init(this);
798
+ }
799
+ };
800
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], App.prototype, "gRouter", void 0);
801
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(PluginsRegistry)], App.prototype, "gPluginsRegistry", void 0);
802
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(HttpServer)], App.prototype, "gHttpServer", void 0);
803
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(StaticRequestHandler)], App.prototype, "gStaticRequestHandler", void 0);
804
+
805
+ //#endregion
806
+ //#region packages/logger/dist/Providers/index.mjs
807
+ var LoggerProvider = class {};
808
+ const isColorAllowed = () => !process.env.NO_COLOR;
809
+ const colorIfAllowed = (colorFn) => {
810
+ const wrappedFn = (text) => {
811
+ return isColorAllowed() ? colorFn(text) : text;
812
+ };
813
+ return wrappedFn;
814
+ };
815
+ const colors = {
816
+ bold: colorIfAllowed((text) => `\x1B[1m${text}\x1B[0m`),
817
+ green: colorIfAllowed((text) => `\x1B[32m${text}\x1B[39m`),
818
+ yellow: colorIfAllowed((text) => `\x1B[33m${text}\x1B[39m`),
819
+ red: colorIfAllowed((text) => `\x1B[31m${text}\x1B[39m`),
820
+ magentaBright: colorIfAllowed((text) => `\x1B[95m${text}\x1B[39m`),
821
+ cyanBright: colorIfAllowed((text) => `\x1B[96m${text}\x1B[39m`)
822
+ };
823
+ const LOG_LEVEL_COLORS = {
824
+ debug: colors.green,
825
+ info: colors.bold,
826
+ warn: colors.yellow,
827
+ error: colors.red
828
+ };
829
+ var ConsoleProvider = class extends LoggerProvider {
830
+ /**
831
+ * Initializes the appender with the provided options.
832
+ * This method should be called before using the appender to process messages.
833
+ */
834
+ initialize() {}
835
+ /**
836
+ * Prints a log message according to the specified format and level.
837
+ * @param message - The log message object containing level, tag, and arguments
838
+ * @protected
839
+ */
840
+ processMessage(message) {
841
+ const date = message.timestamp ? new Date(message.timestamp) : new Date();
842
+ console[message.level](`%s%s${message?.tag ? "%s" : ""} %s`, LOG_LEVEL_COLORS[message.level](`[${date.toISOString().split("T")[1]?.replace("Z", "")}]`), LOG_LEVEL_COLORS[message.level](`[${message.level.toUpperCase().padEnd(5, " ")}]`), message?.tag ? LOG_LEVEL_COLORS[message.level](`[${message.tag}]`) : "", ...message.args);
843
+ }
844
+ };
845
+
846
+ //#endregion
847
+ //#region packages/core/src/Services/Validation/ValidationProvider.ts
848
+ var ValidationProvider = class {};
849
+
850
+ //#endregion
851
+ //#region packages/core/src/Services/Validation/StandardSchemaValidationProvider.ts
852
+ var StandardSchemaValidationProvider = class {
853
+ /**
854
+ * Validates data against a schema
855
+ * @param {ValidationTypes.Schema} schema - The schema to validate against
856
+ * @param {ValidationTypes.Input} data - The data to validate
857
+ * @return {ValidationTypes.Result | Promise<ValidationTypes.Result>} The validation result
858
+ */
859
+ validate(schema, data) {
860
+ return schema["~standard"].validate(data);
861
+ }
862
+ };
863
+
864
+ //#endregion
865
+ //#region packages/core/src/Services/Config/RuntimeConfig.ts
866
+ var RuntimeConfig = class {
867
+ /**
868
+ * Private field to store the runtime configuration object.
869
+ * @private
870
+ */
871
+ fRuntimeConfig;
872
+ /**
873
+ * Gets the current runtime configuration.
874
+ * @returns {ConfigTypes.RuntimeConfig} The current runtime configuration object.
875
+ */
876
+ get runtimeConfig() {
877
+ return this.fRuntimeConfig;
878
+ }
879
+ /**
880
+ * Sets the runtime configuration.
881
+ * @param {ConfigTypes.RuntimeConfig} value - The new runtime configuration object to set.
882
+ */
883
+ set runtimeConfig(value) {
884
+ this.fRuntimeConfig = value;
885
+ }
886
+ };
887
+
888
+ //#endregion
889
+ //#region packages/core/src/Errors/Http/InternalServerError.ts
890
+ var InternalServerError = class InternalServerError extends HttpError {
891
+ /**
892
+ * The name of the error.
893
+ * @type {string}
894
+ */
895
+ name = "InternalServerError";
896
+ /**
897
+ * Creates an instance of InternalServerError.
898
+ * @param {string} [message] - The error message.
899
+ */
900
+ constructor(message) {
901
+ super(500);
902
+ Object.setPrototypeOf(this, InternalServerError.prototype);
903
+ if (message) this.message = message;
904
+ }
905
+ };
906
+
907
+ //#endregion
908
+ //#region packages/core/src/Services/ErrorHandler/DefaultErrorHandlerProvider.ts
909
+ var DefaultErrorHandlerProvider = class extends ErrorHandlerProvider {
910
+ gLogger;
911
+ /**
912
+ * Handles an error that occurred during request processing
913
+ *
914
+ * @param error - The Error object containing error details
915
+ * @returns Promise<Response> | Response - The response to be sent to the client
916
+ */
917
+ handleError(error) {
918
+ const _internalError = new InternalServerError();
919
+ const status = error?.status ?? 500;
920
+ if (error instanceof HttpError) return new Response(JSON.stringify({ ...error }, void 0, 2), { status });
921
+ this.gLogger.error(error);
922
+ return new Response(JSON.stringify({ ...error?.cause ?? _internalError.cause }, void 0, 2), { status });
923
+ }
924
+ };
925
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(__vercube_logger.Logger)], DefaultErrorHandlerProvider.prototype, "gLogger", void 0);
926
+
927
+ //#endregion
928
+ //#region packages/core/src/Common/Container.ts
929
+ function createContainer(config) {
930
+ const container = new __vercube_di.Container();
931
+ container.bindInstance(__vercube_di.Container, container);
932
+ container.bind(__vercube_logger.Logger, __vercube_logger.BaseLogger);
933
+ container.get(__vercube_logger.Logger).configure({
934
+ logLevel: config.logLevel ?? "debug",
935
+ providers: [{
936
+ name: "console",
937
+ provider: ConsoleProvider
938
+ }]
939
+ });
940
+ container.bind(ErrorHandlerProvider, DefaultErrorHandlerProvider);
941
+ container.bind(HttpServer);
942
+ container.bind(StaticRequestHandler);
943
+ container.bind(Router);
944
+ container.bind(HooksService);
945
+ container.bind(MetadataResolver);
946
+ container.bind(PluginsRegistry);
947
+ container.bind(RequestHandler);
948
+ container.bind(RuntimeConfig);
949
+ container.bind(GlobalMiddlewareRegistry);
950
+ container.bind(ValidationProvider, StandardSchemaValidationProvider);
951
+ return container;
952
+ }
953
+
954
+ //#endregion
955
+ //#region packages/core/src/Utils/InternalUtils.ts
956
+ function generateRandomHash() {
957
+ const hashByPerformance = Math.floor(Date.now() * 1e3).toString(16);
958
+ const hashByMath = () => (Math.floor(Math.random() * 16777215) | 1048576).toString(16);
959
+ return `${hashByPerformance}-${hashByMath()}-${hashByMath()}-${hashByMath()}`;
960
+ }
961
+
962
+ //#endregion
963
+ //#region packages/core/src/Config/DefaultConfig.ts
964
+ const defaultConfig = {
965
+ logLevel: "debug",
966
+ production: false,
967
+ dev: false,
968
+ build: {
969
+ root: process.cwd(),
970
+ entry: "src/index.ts",
971
+ output: {
972
+ dir: "dist",
973
+ publicDir: "public"
974
+ },
975
+ bundler: "rolldown"
976
+ },
977
+ server: {
978
+ runtime: "node",
979
+ host: "localhost",
980
+ port: 3e3,
981
+ https: false,
982
+ static: { dirs: ["public"] }
983
+ },
984
+ experimental: {},
985
+ runtime: { session: {
986
+ secret: process.env?.SECRET ?? generateRandomHash(),
987
+ name: "vercube_session",
988
+ duration: 60 * 60 * 24 * 7
989
+ } }
990
+ };
991
+
992
+ //#endregion
993
+ //#region packages/core/src/Config/Loader.ts
994
+ async function loadVercubeConfig(overrides) {
995
+ const config = await (0, c12.loadConfig)({
996
+ name: "vercube",
997
+ dotenv: true,
998
+ rcFile: false,
999
+ globalRc: false,
1000
+ defaults: defaultConfig
1001
+ });
1002
+ return (0, defu.defu)(overrides ?? {}, config?.config ?? {});
1003
+ }
1004
+
1005
+ //#endregion
1006
+ //#region packages/core/src/Common/CreateApp.ts
1007
+ async function createApp(cfg) {
1008
+ const config = await loadVercubeConfig(cfg);
1009
+ const container = createContainer(config);
1010
+ const app = container.resolve(App);
1011
+ container.get(RuntimeConfig).runtimeConfig = config?.runtime ?? {};
1012
+ app.container = container;
1013
+ await app.init(config);
1014
+ (0, __vercube_di.initializeContainer)(container);
1015
+ return app;
1016
+ }
1017
+
1018
+ //#endregion
1019
+ //#region packages/core/src/Config/Config.ts
1020
+ function defineConfig(config) {
1021
+ return config;
1022
+ }
1023
+
1024
+ //#endregion
1025
+ //#region packages/core/src/Middleware/ValidationMiddleware.ts
1026
+ var ValidationMiddleware = class {
1027
+ gValidationProvider;
1028
+ /**
1029
+ * Middleware function that processes the HTTP event
1030
+ * @param {Request} request - The HTTP request object
1031
+ * @param {Response} response - The HTTP response object
1032
+ * @param {MiddlewareOptions} args - Additional arguments for the middleware
1033
+ * @returns {Promise<void>} - A promise that resolves when the processing is complete
1034
+ * @throws {BadRequestError} - If validation fails
1035
+ */
1036
+ async onRequest(request, response, args) {
1037
+ if (!this.gValidationProvider) {
1038
+ console.warn("ValidationMiddleware::ValidationProvider is not registered");
1039
+ return;
1040
+ }
1041
+ const validators = args.methodArgs?.filter((arg) => arg.validate && arg.validationSchema) ?? [];
1042
+ for (const validator of validators) {
1043
+ const result = await this.gValidationProvider.validate(validator.validationSchema, validator.resolved);
1044
+ if (result.issues?.length) throw new BadRequestError(`Validation error - ${validator.type}`, result.issues);
1045
+ }
1046
+ }
1047
+ };
1048
+ (0, import_decorate.default)([(0, __vercube_di.InjectOptional)(ValidationProvider)], ValidationMiddleware.prototype, "gValidationProvider", void 0);
1049
+
1050
+ //#endregion
1051
+ //#region packages/core/src/Utils/Utils.ts
1052
+ function createMetadataCtx() {
1053
+ return {
1054
+ __controller: { path: "" },
1055
+ __middlewares: [],
1056
+ __methods: {}
1057
+ };
1058
+ }
1059
+ function createMetadataMethod() {
1060
+ return {
1061
+ req: null,
1062
+ res: null,
1063
+ url: null,
1064
+ args: [],
1065
+ actions: []
1066
+ };
1067
+ }
1068
+ function initializeMetadataMethod(target, propertyName) {
1069
+ if (!target.__metadata.__methods[propertyName]) target.__metadata.__methods[propertyName] = createMetadataMethod();
1070
+ return target.__metadata.__methods[propertyName];
1071
+ }
1072
+ function initializeMetadata(target) {
1073
+ if (!target.__metadata) target.__metadata = createMetadataCtx();
1074
+ if (!target.__metadata.__methods) target.__metadata.__methods = {};
1075
+ if (!target.__metadata.__middlewares) target.__metadata.__middlewares = [];
1076
+ return target.__metadata;
1077
+ }
1078
+
1079
+ //#endregion
1080
+ //#region packages/core/src/Decorators/Http/Body.ts
1081
+ var BodyDecorator = class extends __vercube_di.BaseDecorator {
1082
+ /**
1083
+ * @method created
1084
+ * This method is called when the decorator is created. It ensures that the metadata
1085
+ * for the property exists and adds the body argument to the metadata.
1086
+ */
1087
+ created() {
1088
+ const meta = initializeMetadata(this.prototype);
1089
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1090
+ method.args.push({
1091
+ idx: this.propertyIndex,
1092
+ type: "body",
1093
+ validate: this.options?.validationSchema ? true : false,
1094
+ validationSchema: this.options?.validationSchema
1095
+ });
1096
+ meta.__middlewares.unshift({
1097
+ target: this.propertyName,
1098
+ priority: -1,
1099
+ args: {},
1100
+ middleware: ValidationMiddleware
1101
+ });
1102
+ }
1103
+ };
1104
+ function Body(options) {
1105
+ return (0, __vercube_di.createDecorator)(BodyDecorator, options);
1106
+ }
1107
+
1108
+ //#endregion
1109
+ //#region packages/core/src/Decorators/Http/Connect.ts
1110
+ var ConnectDecorator = class extends __vercube_di.BaseDecorator {
1111
+ gRouter;
1112
+ gRequestHandler;
1113
+ gMetadataResolver;
1114
+ /**
1115
+ * Called when the decorator is created.
1116
+ *
1117
+ * This method constructs the full path for the route, registers the route
1118
+ * with the Router, and sets up the event handler for the CONNECT request.
1119
+ */
1120
+ created() {
1121
+ this.options.path = this.gMetadataResolver.resolveUrl({
1122
+ instance: this.instance,
1123
+ path: this.options.path,
1124
+ propertyName: this.propertyName
1125
+ });
1126
+ this.gRouter.addRoute({
1127
+ path: this.options.path,
1128
+ method: "CONNECT",
1129
+ handler: this.gRequestHandler.prepareHandler({
1130
+ instance: this.instance,
1131
+ propertyName: this.propertyName
1132
+ })
1133
+ });
1134
+ }
1135
+ };
1136
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], ConnectDecorator.prototype, "gRouter", void 0);
1137
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], ConnectDecorator.prototype, "gRequestHandler", void 0);
1138
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], ConnectDecorator.prototype, "gMetadataResolver", void 0);
1139
+ function Connect(path) {
1140
+ return (0, __vercube_di.createDecorator)(ConnectDecorator, { path });
1141
+ }
1142
+
1143
+ //#endregion
1144
+ //#region packages/core/src/Decorators/Http/Controller.ts
1145
+ function Controller(path) {
1146
+ return function internalDecorator(target) {
1147
+ const meta = initializeMetadata(target.prototype);
1148
+ meta.__controller = {
1149
+ ...meta?.__controller,
1150
+ path
1151
+ };
1152
+ };
1153
+ }
1154
+
1155
+ //#endregion
1156
+ //#region packages/core/src/Decorators/Http/Delete.ts
1157
+ var DeleteDecorator = class extends __vercube_di.BaseDecorator {
1158
+ gRouter;
1159
+ gRequestHandler;
1160
+ gMetadataResolver;
1161
+ /**
1162
+ * Called when the decorator is created.
1163
+ *
1164
+ * This method constructs the full path for the route, registers the route
1165
+ * with the Router, and sets up the event handler for the DELETE request.
1166
+ */
1167
+ created() {
1168
+ initializeMetadata(this.prototype);
1169
+ initializeMetadataMethod(this.prototype, this.propertyName);
1170
+ this.options.path = this.gMetadataResolver.resolveUrl({
1171
+ instance: this.instance,
1172
+ path: this.options.path,
1173
+ propertyName: this.propertyName
1174
+ });
1175
+ this.gRouter.addRoute({
1176
+ path: this.options.path,
1177
+ method: "DELETE",
1178
+ handler: this.gRequestHandler.prepareHandler({
1179
+ instance: this.instance,
1180
+ propertyName: this.propertyName
1181
+ })
1182
+ });
1183
+ }
1184
+ };
1185
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], DeleteDecorator.prototype, "gRouter", void 0);
1186
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], DeleteDecorator.prototype, "gRequestHandler", void 0);
1187
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], DeleteDecorator.prototype, "gMetadataResolver", void 0);
1188
+ function Delete(path) {
1189
+ return (0, __vercube_di.createDecorator)(DeleteDecorator, { path });
1190
+ }
1191
+
1192
+ //#endregion
1193
+ //#region packages/core/src/Decorators/Http/Get.ts
1194
+ var GetDecorator = class extends __vercube_di.BaseDecorator {
1195
+ gRouter;
1196
+ gRequestHandler;
1197
+ gMetadataResolver;
1198
+ /**
1199
+ * Called when the decorator is created.
1200
+ *
1201
+ * This method constructs the full path for the route, registers the route
1202
+ * with the Router, and sets up the event handler for the GET request.
1203
+ */
1204
+ created() {
1205
+ initializeMetadata(this.prototype);
1206
+ initializeMetadataMethod(this.prototype, this.propertyName);
1207
+ this.options.path = this.gMetadataResolver.resolveUrl({
1208
+ instance: this.instance,
1209
+ path: this.options.path,
1210
+ propertyName: this.propertyName
1211
+ });
1212
+ this.gRouter.addRoute({
1213
+ path: this.options.path,
1214
+ method: "GET",
1215
+ handler: this.gRequestHandler.prepareHandler({
1216
+ instance: this.instance,
1217
+ propertyName: this.propertyName
1218
+ })
1219
+ });
1220
+ }
1221
+ };
1222
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], GetDecorator.prototype, "gRouter", void 0);
1223
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], GetDecorator.prototype, "gRequestHandler", void 0);
1224
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], GetDecorator.prototype, "gMetadataResolver", void 0);
1225
+ function Get(path) {
1226
+ return (0, __vercube_di.createDecorator)(GetDecorator, { path });
1227
+ }
1228
+
1229
+ //#endregion
1230
+ //#region packages/core/src/Decorators/Http/Head.ts
1231
+ var HeadDecorator = class extends __vercube_di.BaseDecorator {
1232
+ gRouter;
1233
+ gRequestHandler;
1234
+ gMetadataResolver;
1235
+ /**
1236
+ * Called when the decorator is created.
1237
+ *
1238
+ * This method constructs the full path for the route, registers the route
1239
+ * with the Router, and sets up the event handler for the HEAD request.
1240
+ */
1241
+ created() {
1242
+ initializeMetadata(this.prototype);
1243
+ initializeMetadataMethod(this.prototype, this.propertyName);
1244
+ this.options.path = this.gMetadataResolver.resolveUrl({
1245
+ instance: this.instance,
1246
+ path: this.options.path,
1247
+ propertyName: this.propertyName
1248
+ });
1249
+ this.gRouter.addRoute({
1250
+ path: this.options.path,
1251
+ method: "HEAD",
1252
+ handler: this.gRequestHandler.prepareHandler({
1253
+ instance: this.instance,
1254
+ propertyName: this.propertyName
1255
+ })
1256
+ });
1257
+ }
1258
+ };
1259
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], HeadDecorator.prototype, "gRouter", void 0);
1260
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], HeadDecorator.prototype, "gRequestHandler", void 0);
1261
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], HeadDecorator.prototype, "gMetadataResolver", void 0);
1262
+ function Head(path) {
1263
+ return (0, __vercube_di.createDecorator)(HeadDecorator, { path });
1264
+ }
1265
+
1266
+ //#endregion
1267
+ //#region packages/core/src/Decorators/Http/Header.ts
1268
+ var HeaderDecorator = class extends __vercube_di.BaseDecorator {
1269
+ /**
1270
+ * Called when the decorator is created.
1271
+ *
1272
+ * This method checks if metadata for the property exists, creates it if it doesn't,
1273
+ * and then adds the header information to the metadata.
1274
+ */
1275
+ created() {
1276
+ initializeMetadata(this.prototype);
1277
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1278
+ method.args.push({
1279
+ idx: this.propertyIndex,
1280
+ type: "header",
1281
+ data: { name: this.options.name }
1282
+ });
1283
+ }
1284
+ };
1285
+ function Header(name) {
1286
+ return (0, __vercube_di.createDecorator)(HeaderDecorator, { name });
1287
+ }
1288
+
1289
+ //#endregion
1290
+ //#region packages/core/src/Decorators/Http/Headers.ts
1291
+ var HeadersDecorator = class extends __vercube_di.BaseDecorator {
1292
+ /**
1293
+ * Called when the decorator is created.
1294
+ *
1295
+ * This method checks if metadata for the property exists, creates it if it doesn't,
1296
+ * and then adds the headers information to the metadata.
1297
+ */
1298
+ created() {
1299
+ initializeMetadata(this.prototype);
1300
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1301
+ method.args.push({
1302
+ idx: this.propertyIndex,
1303
+ type: "headers"
1304
+ });
1305
+ }
1306
+ };
1307
+ function Headers$1() {
1308
+ return (0, __vercube_di.createDecorator)(HeadersDecorator, {});
1309
+ }
1310
+
1311
+ //#endregion
1312
+ //#region packages/core/src/Decorators/Http/Options.ts
1313
+ var OptionsDecorator = class extends __vercube_di.BaseDecorator {
1314
+ gRouter;
1315
+ gRequestHandler;
1316
+ gMetadataResolver;
1317
+ /**
1318
+ * Called when the decorator is created.
1319
+ *
1320
+ * This method constructs the full path for the route, registers the route
1321
+ * with the Router, and sets up the event handler for the OPTIONS request.
1322
+ */
1323
+ created() {
1324
+ initializeMetadata(this.prototype);
1325
+ initializeMetadataMethod(this.prototype, this.propertyName);
1326
+ this.options.path = this.gMetadataResolver.resolveUrl({
1327
+ instance: this.instance,
1328
+ path: this.options.path,
1329
+ propertyName: this.propertyName
1330
+ });
1331
+ this.gRouter.addRoute({
1332
+ path: this.options.path,
1333
+ method: "OPTIONS",
1334
+ handler: this.gRequestHandler.prepareHandler({
1335
+ instance: this.instance,
1336
+ propertyName: this.propertyName
1337
+ })
1338
+ });
1339
+ }
1340
+ };
1341
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], OptionsDecorator.prototype, "gRouter", void 0);
1342
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], OptionsDecorator.prototype, "gRequestHandler", void 0);
1343
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], OptionsDecorator.prototype, "gMetadataResolver", void 0);
1344
+ function Options(path) {
1345
+ return (0, __vercube_di.createDecorator)(OptionsDecorator, { path });
1346
+ }
1347
+
1348
+ //#endregion
1349
+ //#region packages/core/src/Decorators/Http/Param.ts
1350
+ var ParamDecorator = class extends __vercube_di.BaseDecorator {
1351
+ gMetadataResolver;
1352
+ /**
1353
+ * Called when the decorator is created.
1354
+ *
1355
+ * This method checks if metadata for the property exists, creates it if it doesn't,
1356
+ * and then adds the parameter information to the metadata.
1357
+ */
1358
+ created() {
1359
+ initializeMetadata(this.prototype);
1360
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1361
+ method.args.push({
1362
+ idx: this.propertyIndex,
1363
+ type: "param",
1364
+ data: { name: this.options.name }
1365
+ });
1366
+ }
1367
+ };
1368
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], ParamDecorator.prototype, "gMetadataResolver", void 0);
1369
+ function Param(name) {
1370
+ return (0, __vercube_di.createDecorator)(ParamDecorator, { name });
1371
+ }
1372
+
1373
+ //#endregion
1374
+ //#region packages/core/src/Decorators/Http/Patch.ts
1375
+ var PatchDecorator = class extends __vercube_di.BaseDecorator {
1376
+ gRouter;
1377
+ gRequestHandler;
1378
+ gMetadataResolver;
1379
+ /**
1380
+ * Called when the decorator is created.
1381
+ *
1382
+ * This method constructs the full path for the route, registers the route
1383
+ * with the Router, and sets up the event handler for the PATCH request.
1384
+ */
1385
+ created() {
1386
+ this.options.path = this.gMetadataResolver.resolveUrl({
1387
+ instance: this.instance,
1388
+ path: this.options.path,
1389
+ propertyName: this.propertyName
1390
+ });
1391
+ this.gRouter.addRoute({
1392
+ path: this.options.path,
1393
+ method: "PATCH",
1394
+ handler: this.gRequestHandler.prepareHandler({
1395
+ instance: this.instance,
1396
+ propertyName: this.propertyName
1397
+ })
1398
+ });
1399
+ }
1400
+ };
1401
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], PatchDecorator.prototype, "gRouter", void 0);
1402
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], PatchDecorator.prototype, "gRequestHandler", void 0);
1403
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], PatchDecorator.prototype, "gMetadataResolver", void 0);
1404
+ function Patch(path) {
1405
+ return (0, __vercube_di.createDecorator)(PatchDecorator, { path });
1406
+ }
1407
+
1408
+ //#endregion
1409
+ //#region packages/core/src/Decorators/Http/Post.ts
1410
+ var PostDecorator = class extends __vercube_di.BaseDecorator {
1411
+ gRouter;
1412
+ gMetadataResolver;
1413
+ gRequestHandler;
1414
+ /**
1415
+ * Called when the decorator is created.
1416
+ *
1417
+ * This method constructs the full path for the route, registers the route
1418
+ * with the Router, and sets up the event handler for the POST request.
1419
+ */
1420
+ created() {
1421
+ initializeMetadata(this.prototype);
1422
+ initializeMetadataMethod(this.prototype, this.propertyName);
1423
+ this.options.path = this.gMetadataResolver.resolveUrl({
1424
+ instance: this.instance,
1425
+ path: this.options.path,
1426
+ propertyName: this.propertyName
1427
+ });
1428
+ this.gRouter.addRoute({
1429
+ path: this.options.path,
1430
+ method: "POST",
1431
+ handler: this.gRequestHandler.prepareHandler({
1432
+ instance: this.instance,
1433
+ propertyName: this.propertyName
1434
+ })
1435
+ });
1436
+ }
1437
+ };
1438
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], PostDecorator.prototype, "gRouter", void 0);
1439
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], PostDecorator.prototype, "gMetadataResolver", void 0);
1440
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], PostDecorator.prototype, "gRequestHandler", void 0);
1441
+ function Post(path) {
1442
+ return (0, __vercube_di.createDecorator)(PostDecorator, { path });
1443
+ }
1444
+
1445
+ //#endregion
1446
+ //#region packages/core/src/Decorators/Http/Put.ts
1447
+ var PutDecorator = class extends __vercube_di.BaseDecorator {
1448
+ gRouter;
1449
+ gRequestHandler;
1450
+ gMetadataResolver;
1451
+ /**
1452
+ * Called when the decorator is created.
1453
+ *
1454
+ * This method constructs the full path for the route, registers the route
1455
+ * with the Router, and sets up the event handler for the PUT request.
1456
+ */
1457
+ created() {
1458
+ initializeMetadata(this.prototype);
1459
+ initializeMetadataMethod(this.prototype, this.propertyName);
1460
+ this.options.path = this.gMetadataResolver.resolveUrl({
1461
+ instance: this.instance,
1462
+ path: this.options.path,
1463
+ propertyName: this.propertyName
1464
+ });
1465
+ this.gRouter.addRoute({
1466
+ path: this.options.path,
1467
+ method: "PUT",
1468
+ handler: this.gRequestHandler.prepareHandler({
1469
+ instance: this.instance,
1470
+ propertyName: this.propertyName
1471
+ })
1472
+ });
1473
+ }
1474
+ };
1475
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], PutDecorator.prototype, "gRouter", void 0);
1476
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], PutDecorator.prototype, "gRequestHandler", void 0);
1477
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], PutDecorator.prototype, "gMetadataResolver", void 0);
1478
+ function Put(path) {
1479
+ return (0, __vercube_di.createDecorator)(PutDecorator, { path });
1480
+ }
1481
+
1482
+ //#endregion
1483
+ //#region packages/core/src/Decorators/Http/QueryParam.ts
1484
+ var QueryParamDecorator = class extends __vercube_di.BaseDecorator {
1485
+ /**
1486
+ * Called when the decorator is created.
1487
+ *
1488
+ * This method checks if metadata for the property exists, creates it if it doesn't,
1489
+ * and then adds the query parameter information to the metadata.
1490
+ */
1491
+ created() {
1492
+ const meta = initializeMetadata(this.prototype);
1493
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1494
+ method.args.push({
1495
+ idx: this.propertyIndex,
1496
+ type: "query-param",
1497
+ data: { name: this.options.name },
1498
+ validate: this.options?.validationSchema ? true : false,
1499
+ validationSchema: this.options?.validationSchema
1500
+ });
1501
+ meta.__middlewares.unshift({
1502
+ target: this.propertyName,
1503
+ priority: -1,
1504
+ args: {},
1505
+ middleware: ValidationMiddleware
1506
+ });
1507
+ }
1508
+ };
1509
+ function QueryParam(options) {
1510
+ return (0, __vercube_di.createDecorator)(QueryParamDecorator, options);
1511
+ }
1512
+
1513
+ //#endregion
1514
+ //#region packages/core/src/Decorators/Http/QueryParams.ts
1515
+ var QueryParamsDecorator = class extends __vercube_di.BaseDecorator {
1516
+ /**
1517
+ * Called when the decorator is created.
1518
+ *
1519
+ * This method checks if metadata for the property exists, creates it if it doesn't,
1520
+ * and then adds the query parameters information to the metadata.
1521
+ */
1522
+ created() {
1523
+ const meta = initializeMetadata(this.prototype);
1524
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1525
+ method.args.push({
1526
+ idx: this.propertyIndex,
1527
+ type: "query-params",
1528
+ data: {},
1529
+ validate: this.options?.validationSchema ? true : false,
1530
+ validationSchema: this.options?.validationSchema
1531
+ });
1532
+ meta.__middlewares.unshift({
1533
+ target: this.propertyName,
1534
+ priority: -1,
1535
+ args: {},
1536
+ middleware: ValidationMiddleware
1537
+ });
1538
+ }
1539
+ };
1540
+ function QueryParams(options) {
1541
+ return (0, __vercube_di.createDecorator)(QueryParamsDecorator, options);
1542
+ }
1543
+
1544
+ //#endregion
1545
+ //#region packages/core/src/Decorators/Http/Request.ts
1546
+ var RequestDecorator = class extends __vercube_di.BaseDecorator {
1547
+ /**
1548
+ * Called when the decorator is created.
1549
+ *
1550
+ * This method checks if metadata for the property exists, creates it if it doesn't,
1551
+ * and then adds the request information to the metadata.
1552
+ */
1553
+ created() {
1554
+ initializeMetadata(this.prototype);
1555
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1556
+ method.args.push({
1557
+ idx: this.propertyIndex,
1558
+ type: "request"
1559
+ });
1560
+ }
1561
+ };
1562
+ function Request() {
1563
+ return (0, __vercube_di.createDecorator)(RequestDecorator, {});
1564
+ }
1565
+
1566
+ //#endregion
1567
+ //#region packages/core/src/Decorators/Http/Response.ts
1568
+ var ResponseDecorator = class extends __vercube_di.BaseDecorator {
1569
+ /**
1570
+ * Called when the decorator is created.
1571
+ *
1572
+ * This method checks if metadata for the property exists, creates it if it doesn't,
1573
+ * and then adds the response information to the metadata.
1574
+ */
1575
+ created() {
1576
+ initializeMetadata(this.prototype);
1577
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1578
+ method.args.push({
1579
+ idx: this.propertyIndex,
1580
+ type: "response"
1581
+ });
1582
+ }
1583
+ };
1584
+ function Response$1() {
1585
+ return (0, __vercube_di.createDecorator)(ResponseDecorator, {});
1586
+ }
1587
+
1588
+ //#endregion
1589
+ //#region packages/core/src/Decorators/Http/Trace.ts
1590
+ var TraceDecorator = class extends __vercube_di.BaseDecorator {
1591
+ gRouter;
1592
+ gRequestHandler;
1593
+ gMetadataResolver;
1594
+ /**
1595
+ * Called when the decorator is created.
1596
+ *
1597
+ * This method constructs the full path for the route, registers the route
1598
+ * with the Router, and sets up the event handler for the TRACE request.
1599
+ */
1600
+ created() {
1601
+ initializeMetadata(this.prototype);
1602
+ initializeMetadataMethod(this.prototype, this.propertyName);
1603
+ this.options.path = this.gMetadataResolver.resolveUrl({
1604
+ instance: this.instance,
1605
+ path: this.options.path,
1606
+ propertyName: this.propertyName
1607
+ });
1608
+ this.gRouter.addRoute({
1609
+ path: this.options.path,
1610
+ method: "TRACE",
1611
+ handler: this.gRequestHandler.prepareHandler({
1612
+ instance: this.instance,
1613
+ propertyName: this.propertyName
1614
+ })
1615
+ });
1616
+ }
1617
+ };
1618
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(Router)], TraceDecorator.prototype, "gRouter", void 0);
1619
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RequestHandler)], TraceDecorator.prototype, "gRequestHandler", void 0);
1620
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(MetadataResolver)], TraceDecorator.prototype, "gMetadataResolver", void 0);
1621
+ function Trace(path) {
1622
+ return (0, __vercube_di.createDecorator)(TraceDecorator, { path });
1623
+ }
1624
+
1625
+ //#endregion
1626
+ //#region packages/core/src/Decorators/Http/SetHeader.ts
1627
+ var SetHeaderDecorator = class extends __vercube_di.BaseDecorator {
1628
+ /**
1629
+ * Called when the decorator is created.
1630
+ * Adds a query parameter to the metadata.
1631
+ * @override
1632
+ */
1633
+ created() {
1634
+ initializeMetadata(this.prototype);
1635
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1636
+ method.actions.push({ handler: (req, res) => {
1637
+ res.headers.delete(this.options.key);
1638
+ res.headers.append(this.options.key, this.options.value);
1639
+ return res;
1640
+ } });
1641
+ }
1642
+ };
1643
+ function SetHeader(key, value) {
1644
+ return (0, __vercube_di.createDecorator)(SetHeaderDecorator, {
1645
+ key,
1646
+ value
1647
+ });
1648
+ }
1649
+
1650
+ //#endregion
1651
+ //#region packages/core/src/Decorators/Http/Status.ts
1652
+ var StatusDecorator = class extends __vercube_di.BaseDecorator {
1653
+ /**
1654
+
1655
+ * Called when the decorator is created.
1656
+
1657
+ * Sets a status on the response
1658
+
1659
+ * @override
1660
+
1661
+ */
1662
+ created() {
1663
+ initializeMetadata(this.prototype);
1664
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1665
+ method.actions.push({ handler: () => ({ status: this.options.code }) });
1666
+ }
1667
+ };
1668
+ function Status(code) {
1669
+ return (0, __vercube_di.createDecorator)(StatusDecorator, { code });
1670
+ }
1671
+
1672
+ //#endregion
1673
+ //#region packages/core/src/Decorators/Http/Redirect.ts
1674
+ var RedirectDecorator = class extends __vercube_di.BaseDecorator {
1675
+ /**
1676
+
1677
+ * Decorator responsible for redirecting to a specified URL.
1678
+
1679
+ * Called when the decorator is created.
1680
+
1681
+ * Sets the location header value and status code.
1682
+
1683
+ * @override
1684
+
1685
+ */
1686
+ created() {
1687
+ initializeMetadata(this.prototype);
1688
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1689
+ method.actions.push({ handler: () => {
1690
+ return new Response(void 0, {
1691
+ status: this.options.code,
1692
+ headers: { "Location": this.options.location }
1693
+ });
1694
+ } });
1695
+ }
1696
+ };
1697
+ function Redirect(location, code = 301) {
1698
+ return (0, __vercube_di.createDecorator)(RedirectDecorator, {
1699
+ location,
1700
+ code
1701
+ });
1702
+ }
1703
+
1704
+ //#endregion
1705
+ //#region packages/core/src/Decorators/Http/Middleware.ts
1706
+ function Middleware(middleware, opts) {
1707
+ return function internalDecorator(target, propertyName) {
1708
+ const ctx = propertyName ? target : target.prototype;
1709
+ const meta = initializeMetadata(ctx);
1710
+ meta.__middlewares.push({
1711
+ target: propertyName ?? "__global__",
1712
+ priority: opts?.priority ?? 999,
1713
+ middleware
1714
+ });
1715
+ };
1716
+ }
1717
+
1718
+ //#endregion
1719
+ //#region packages/core/src/Decorators/Http/MultipartFormData.ts
1720
+ var MultipartFormDataDecorator = class extends __vercube_di.BaseDecorator {
1721
+ /**
1722
+ * @method created
1723
+ * This method is called when the decorator is created. It ensures that the metadata
1724
+ * for the property exists and adds the body argument to the metadata.
1725
+ */
1726
+ created() {
1727
+ initializeMetadata(this.prototype);
1728
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1729
+ method.args.push({
1730
+ idx: this.propertyIndex,
1731
+ type: "multipart-form-data"
1732
+ });
1733
+ }
1734
+ };
1735
+ function MultipartFormData() {
1736
+ return (0, __vercube_di.createDecorator)(MultipartFormDataDecorator, {});
1737
+ }
1738
+
1739
+ //#endregion
1740
+ //#region packages/core/src/Decorators/Http/Session.ts
1741
+ var SessionDecorator = class extends __vercube_di.BaseDecorator {
1742
+ gRuntimeConfig;
1743
+ /**
1744
+ * Called when the decorator is created.
1745
+ *
1746
+ * This method checks if metadata for the property exists, creates it if it doesn't,
1747
+ * and then adds the session information to the metadata.
1748
+ */
1749
+ created() {
1750
+ initializeMetadata(this.prototype);
1751
+ const method = initializeMetadataMethod(this.prototype, this.propertyName);
1752
+ method.args.push({
1753
+ idx: this.propertyIndex,
1754
+ type: "session",
1755
+ data: {
1756
+ name: this.gRuntimeConfig.runtimeConfig.session?.name ?? "vercube_session",
1757
+ secret: this.gRuntimeConfig.runtimeConfig.session?.secret ?? generateRandomHash(),
1758
+ duration: this.gRuntimeConfig.runtimeConfig.session?.duration ?? 60 * 60 * 24 * 7
1759
+ }
1760
+ });
1761
+ }
1762
+ };
1763
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(RuntimeConfig)], SessionDecorator.prototype, "gRuntimeConfig", void 0);
1764
+ function Session() {
1765
+ return (0, __vercube_di.createDecorator)(SessionDecorator, {});
1766
+ }
1767
+
1768
+ //#endregion
1769
+ //#region packages/core/src/Decorators/Hooks/Listen.ts
1770
+ var ListenDecorator = class extends __vercube_di.BaseDecorator {
1771
+ gHooksService;
1772
+ fHook;
1773
+ /**
1774
+ * Called when decorator is initialized. It will register event listener that will call this function
1775
+ * once executed.
1776
+ */
1777
+ created() {
1778
+ this.fHook = this.gHooksService.on(this.options.hookType, (data) => this.instance[this.propertyName](data));
1779
+ }
1780
+ /**
1781
+ * Called when decorator is destroyed. It will unregister event listener.
1782
+ */
1783
+ destroyed() {
1784
+ this.gHooksService.off(this.fHook);
1785
+ }
1786
+ };
1787
+ (0, import_decorate.default)([(0, __vercube_di.Inject)(HooksService)], ListenDecorator.prototype, "gHooksService", void 0);
1788
+ function Listen(hookType) {
1789
+ return (0, __vercube_di.createDecorator)(ListenDecorator, { hookType });
1790
+ }
1791
+
1792
+ //#endregion
1793
+ //#region packages/core/src/Services/Plugins/BasePlugin.ts
1794
+ var BasePlugin = class {
1795
+ /**
1796
+ * The name of the plugin.
1797
+ */
1798
+ name;
1799
+ /**
1800
+ * Uses the plugin with the given app.
1801
+ * @param {App} app - The application instance.
1802
+ * @returns {void | Promise<void>} - A void or a promise that resolves to void.
1803
+ */
1804
+ use(app, options) {}
1805
+ };
1806
+
1807
+ //#endregion
1808
+ //#region packages/core/src/Services/Middleware/BaseMiddleware.ts
1809
+ var BaseMiddleware = class {};
1810
+
1811
+ //#endregion
1812
+ //#region packages/core/src/Errors/Http/ForbiddenError.ts
1813
+ var ForbiddenError = class ForbiddenError extends HttpError {
1814
+ /**
1815
+ * The name of the error.
1816
+ * @type {string}
1817
+ */
1818
+ name = "ForbiddenError";
1819
+ /**
1820
+ * Creates an instance of ForbiddenError.
1821
+ * @param {string} [message] - The error message.
1822
+ */
1823
+ constructor(message) {
1824
+ super(403);
1825
+ Object.setPrototypeOf(this, ForbiddenError.prototype);
1826
+ if (message) this.message = message;
1827
+ }
1828
+ };
1829
+
1830
+ //#endregion
1831
+ //#region packages/core/src/Errors/Http/MethodNotAllowedError.ts
1832
+ var MethodNotAllowedError = class MethodNotAllowedError extends HttpError {
1833
+ /**
1834
+ * The name of the error.
1835
+ * @type {string}
1836
+ */
1837
+ name = "MethodNotAllowedError";
1838
+ /**
1839
+ * Creates an instance of MethodNotAllowedError.
1840
+ * @param {string} [message] - The error message.
1841
+ */
1842
+ constructor(message) {
1843
+ super(405);
1844
+ Object.setPrototypeOf(this, MethodNotAllowedError.prototype);
1845
+ if (message) this.message = message;
1846
+ }
1847
+ };
1848
+
1849
+ //#endregion
1850
+ //#region packages/core/src/Errors/Http/NotAcceptableError.ts
1851
+ var NotAcceptableError = class NotAcceptableError extends HttpError {
1852
+ /**
1853
+ * The name of the error.
1854
+ * @type {string}
1855
+ */
1856
+ name = "NotAcceptableError";
1857
+ /**
1858
+ * Creates an instance of NotAcceptableError.
1859
+ * @param {string} [message] - The error message.
1860
+ */
1861
+ constructor(message) {
1862
+ super(406);
1863
+ Object.setPrototypeOf(this, NotAcceptableError.prototype);
1864
+ if (message) this.message = message;
1865
+ }
1866
+ };
1867
+
1868
+ //#endregion
1869
+ //#region packages/core/src/Errors/Http/NotFoundError.ts
1870
+ var NotFoundError = class NotFoundError extends HttpError {
1871
+ /**
1872
+ * The name of the error.
1873
+ * @type {string}
1874
+ */
1875
+ name = "NotFoundError";
1876
+ /**
1877
+ * Creates an instance of NotFoundError.
1878
+ * @param {string} [message] - The error message.
1879
+ */
1880
+ constructor(message) {
1881
+ super(404);
1882
+ Object.setPrototypeOf(this, NotFoundError.prototype);
1883
+ if (message) this.message = message;
1884
+ }
1885
+ };
1886
+
1887
+ //#endregion
1888
+ //#region packages/core/src/Errors/Http/UnauthorizedError.ts
1889
+ var UnauthorizedError = class UnauthorizedError extends HttpError {
1890
+ /**
1891
+ * The name of the error.
1892
+ * @type {string}
1893
+ */
1894
+ name = "UnauthorizedError";
1895
+ /**
1896
+ * Creates an instance of UnauthorizedError.
1897
+ * @param {string} [message] - The error message.
1898
+ */
1899
+ constructor(message) {
1900
+ super(401);
1901
+ Object.setPrototypeOf(this, UnauthorizedError.prototype);
1902
+ if (message) this.message = message;
1903
+ }
1904
+ };
1905
+
1906
+ //#endregion
1907
+ //#region packages/core/src/Types/HttpTypes.ts
1908
+ let HTTPStatus = /* @__PURE__ */ function(HTTPStatus$1) {
1909
+ HTTPStatus$1[HTTPStatus$1["CONTINUE"] = 100] = "CONTINUE";
1910
+ HTTPStatus$1[HTTPStatus$1["SWITCHING_PROTOCOLS"] = 101] = "SWITCHING_PROTOCOLS";
1911
+ HTTPStatus$1[HTTPStatus$1["PROCESSING"] = 102] = "PROCESSING";
1912
+ HTTPStatus$1[HTTPStatus$1["OK"] = 200] = "OK";
1913
+ HTTPStatus$1[HTTPStatus$1["CREATED"] = 201] = "CREATED";
1914
+ HTTPStatus$1[HTTPStatus$1["ACCEPTED"] = 202] = "ACCEPTED";
1915
+ HTTPStatus$1[HTTPStatus$1["NON_AUTHORITATIVE_INFORMATION"] = 203] = "NON_AUTHORITATIVE_INFORMATION";
1916
+ HTTPStatus$1[HTTPStatus$1["NO_CONTENT"] = 204] = "NO_CONTENT";
1917
+ HTTPStatus$1[HTTPStatus$1["RESET_CONTENT"] = 205] = "RESET_CONTENT";
1918
+ HTTPStatus$1[HTTPStatus$1["PARTIAL_CONTENT"] = 206] = "PARTIAL_CONTENT";
1919
+ HTTPStatus$1[HTTPStatus$1["MULTI_STATUS"] = 207] = "MULTI_STATUS";
1920
+ HTTPStatus$1[HTTPStatus$1["ALREADY_REPORTED"] = 208] = "ALREADY_REPORTED";
1921
+ HTTPStatus$1[HTTPStatus$1["IM_USED"] = 226] = "IM_USED";
1922
+ HTTPStatus$1[HTTPStatus$1["MULTIPLE_CHOICES"] = 300] = "MULTIPLE_CHOICES";
1923
+ HTTPStatus$1[HTTPStatus$1["MOVED_PERMANENTLY"] = 301] = "MOVED_PERMANENTLY";
1924
+ HTTPStatus$1[HTTPStatus$1["FOUND"] = 302] = "FOUND";
1925
+ HTTPStatus$1[HTTPStatus$1["SEE_OTHER"] = 303] = "SEE_OTHER";
1926
+ HTTPStatus$1[HTTPStatus$1["NOT_MODIFIED"] = 304] = "NOT_MODIFIED";
1927
+ HTTPStatus$1[HTTPStatus$1["USE_PROXY"] = 305] = "USE_PROXY";
1928
+ HTTPStatus$1[HTTPStatus$1["TEMPORARY_REDIRECT"] = 307] = "TEMPORARY_REDIRECT";
1929
+ HTTPStatus$1[HTTPStatus$1["PERMANENT_REDIRECT"] = 308] = "PERMANENT_REDIRECT";
1930
+ HTTPStatus$1[HTTPStatus$1["BAD_REQUEST"] = 400] = "BAD_REQUEST";
1931
+ HTTPStatus$1[HTTPStatus$1["UNAUTHORIZED"] = 401] = "UNAUTHORIZED";
1932
+ HTTPStatus$1[HTTPStatus$1["PAYMENT_REQUIRED"] = 402] = "PAYMENT_REQUIRED";
1933
+ HTTPStatus$1[HTTPStatus$1["FORBIDDEN"] = 403] = "FORBIDDEN";
1934
+ HTTPStatus$1[HTTPStatus$1["NOT_FOUND"] = 404] = "NOT_FOUND";
1935
+ HTTPStatus$1[HTTPStatus$1["METHOD_NOT_ALLOWED"] = 405] = "METHOD_NOT_ALLOWED";
1936
+ HTTPStatus$1[HTTPStatus$1["NOT_ACCEPTABLE"] = 406] = "NOT_ACCEPTABLE";
1937
+ HTTPStatus$1[HTTPStatus$1["PROXY_AUTHENTICATION_REQUIRED"] = 407] = "PROXY_AUTHENTICATION_REQUIRED";
1938
+ HTTPStatus$1[HTTPStatus$1["REQUEST_TIMEOUT"] = 408] = "REQUEST_TIMEOUT";
1939
+ HTTPStatus$1[HTTPStatus$1["CONFLICT"] = 409] = "CONFLICT";
1940
+ HTTPStatus$1[HTTPStatus$1["GONE"] = 410] = "GONE";
1941
+ HTTPStatus$1[HTTPStatus$1["LENGTH_REQUIRED"] = 411] = "LENGTH_REQUIRED";
1942
+ HTTPStatus$1[HTTPStatus$1["PRECONDITION_FAILED"] = 412] = "PRECONDITION_FAILED";
1943
+ HTTPStatus$1[HTTPStatus$1["PAYLOAD_TOO_LARGE"] = 413] = "PAYLOAD_TOO_LARGE";
1944
+ HTTPStatus$1[HTTPStatus$1["URI_TOO_LONG"] = 414] = "URI_TOO_LONG";
1945
+ HTTPStatus$1[HTTPStatus$1["UNSUPPORTED_MEDIA_TYPE"] = 415] = "UNSUPPORTED_MEDIA_TYPE";
1946
+ HTTPStatus$1[HTTPStatus$1["RANGE_NOT_SATISFIABLE"] = 416] = "RANGE_NOT_SATISFIABLE";
1947
+ HTTPStatus$1[HTTPStatus$1["EXPECTATION_FAILED"] = 417] = "EXPECTATION_FAILED";
1948
+ HTTPStatus$1[HTTPStatus$1["I_AM_A_TEAPOT"] = 418] = "I_AM_A_TEAPOT";
1949
+ HTTPStatus$1[HTTPStatus$1["MISDIRECTED_REQUEST"] = 421] = "MISDIRECTED_REQUEST";
1950
+ HTTPStatus$1[HTTPStatus$1["UNPROCESSABLE_ENTITY"] = 422] = "UNPROCESSABLE_ENTITY";
1951
+ HTTPStatus$1[HTTPStatus$1["LOCKED"] = 423] = "LOCKED";
1952
+ HTTPStatus$1[HTTPStatus$1["FAILED_DEPENDENCY"] = 424] = "FAILED_DEPENDENCY";
1953
+ HTTPStatus$1[HTTPStatus$1["TOO_EARLY"] = 425] = "TOO_EARLY";
1954
+ HTTPStatus$1[HTTPStatus$1["UPGRADE_REQUIRED"] = 426] = "UPGRADE_REQUIRED";
1955
+ HTTPStatus$1[HTTPStatus$1["PRECONDITION_REQUIRED"] = 428] = "PRECONDITION_REQUIRED";
1956
+ HTTPStatus$1[HTTPStatus$1["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
1957
+ HTTPStatus$1[HTTPStatus$1["REQUEST_HEADER_FIELDS_TOO_LARGE"] = 431] = "REQUEST_HEADER_FIELDS_TOO_LARGE";
1958
+ HTTPStatus$1[HTTPStatus$1["UNAVAILABLE_FOR_LEGAL_REASONS"] = 451] = "UNAVAILABLE_FOR_LEGAL_REASONS";
1959
+ HTTPStatus$1[HTTPStatus$1["INTERNAL_SERVER_ERROR"] = 500] = "INTERNAL_SERVER_ERROR";
1960
+ HTTPStatus$1[HTTPStatus$1["NOT_IMPLEMENTED"] = 501] = "NOT_IMPLEMENTED";
1961
+ HTTPStatus$1[HTTPStatus$1["BAD_GATEWAY"] = 502] = "BAD_GATEWAY";
1962
+ HTTPStatus$1[HTTPStatus$1["SERVICE_UNAVAILABLE"] = 503] = "SERVICE_UNAVAILABLE";
1963
+ HTTPStatus$1[HTTPStatus$1["GATEWAY_TIMEOUT"] = 504] = "GATEWAY_TIMEOUT";
1964
+ HTTPStatus$1[HTTPStatus$1["HTTP_VERSION_NOT_SUPPORTED"] = 505] = "HTTP_VERSION_NOT_SUPPORTED";
1965
+ HTTPStatus$1[HTTPStatus$1["VARIANT_ALSO_NEGOTIATES"] = 506] = "VARIANT_ALSO_NEGOTIATES";
1966
+ HTTPStatus$1[HTTPStatus$1["INSUFFICIENT_STORAGE"] = 507] = "INSUFFICIENT_STORAGE";
1967
+ HTTPStatus$1[HTTPStatus$1["LOOP_DETECTED"] = 508] = "LOOP_DETECTED";
1968
+ HTTPStatus$1[HTTPStatus$1["NOT_EXTENDED"] = 510] = "NOT_EXTENDED";
1969
+ HTTPStatus$1[HTTPStatus$1["NETWORK_AUTHENTICATION_REQUIRED"] = 511] = "NETWORK_AUTHENTICATION_REQUIRED";
1970
+ return HTTPStatus$1;
1971
+ }({});
1972
+
1973
+ //#endregion
1974
+ exports.App = App
1975
+ exports.BadRequestError = BadRequestError
1976
+ exports.BaseMiddleware = BaseMiddleware
1977
+ exports.BasePlugin = BasePlugin
1978
+ exports.Body = Body
1979
+ exports.Connect = Connect
1980
+ exports.Controller = Controller
1981
+ exports.Delete = Delete
1982
+ exports.ForbiddenError = ForbiddenError
1983
+ exports.Get = Get
1984
+ exports.HTTPStatus = HTTPStatus
1985
+ exports.Head = Head
1986
+ exports.Header = Header
1987
+ exports.Headers = Headers$1
1988
+ exports.HooksService = HooksService
1989
+ exports.HttpError = HttpError
1990
+ exports.InternalServerError = InternalServerError
1991
+ exports.Listen = Listen
1992
+ exports.MethodNotAllowedError = MethodNotAllowedError
1993
+ exports.Middleware = Middleware
1994
+ exports.MultipartFormData = MultipartFormData
1995
+ exports.NotAcceptableError = NotAcceptableError
1996
+ exports.NotFoundError = NotFoundError
1997
+ exports.Options = Options
1998
+ exports.Param = Param
1999
+ exports.Patch = Patch
2000
+ exports.Post = Post
2001
+ exports.Put = Put
2002
+ exports.QueryParam = QueryParam
2003
+ exports.QueryParams = QueryParams
2004
+ exports.Redirect = Redirect
2005
+ exports.Request = Request
2006
+ exports.Response = Response$1
2007
+ exports.Session = Session
2008
+ exports.SetHeader = SetHeader
2009
+ exports.Status = Status
2010
+ exports.Trace = Trace
2011
+ exports.UnauthorizedError = UnauthorizedError
2012
+ exports.createApp = createApp
2013
+ exports.createMetadataCtx = createMetadataCtx
2014
+ exports.createMetadataMethod = createMetadataMethod
2015
+ exports.defineConfig = defineConfig
2016
+ exports.initializeMetadata = initializeMetadata
2017
+ exports.initializeMetadataMethod = initializeMetadataMethod
2018
+ exports.loadVercubeConfig = loadVercubeConfig