balda-js 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/lib/cli.d.ts +6 -0
  2. package/lib/cli.js +929 -0
  3. package/lib/cli.js.map +1 -0
  4. package/lib/index.cjs +3384 -0
  5. package/lib/index.cjs.map +1 -0
  6. package/lib/index.d.cts +1492 -0
  7. package/lib/index.d.ts +1492 -0
  8. package/lib/index.js +3327 -0
  9. package/lib/index.js.map +1 -0
  10. package/package.json +1 -1
  11. package/.husky/pre-commit +0 -19
  12. package/.nvmrc +0 -1
  13. package/docs/README.md +0 -135
  14. package/docs/blog/authors.yml +0 -6
  15. package/docs/blog/tags.yml +0 -4
  16. package/docs/cli.md +0 -109
  17. package/docs/docs/core-concepts/controllers.md +0 -393
  18. package/docs/docs/core-concepts/middleware.md +0 -302
  19. package/docs/docs/core-concepts/request-response.md +0 -486
  20. package/docs/docs/core-concepts/routing.md +0 -388
  21. package/docs/docs/core-concepts/server.md +0 -332
  22. package/docs/docs/cron/overview.md +0 -70
  23. package/docs/docs/examples/rest-api.md +0 -595
  24. package/docs/docs/getting-started/configuration.md +0 -168
  25. package/docs/docs/getting-started/installation.md +0 -125
  26. package/docs/docs/getting-started/quick-start.md +0 -273
  27. package/docs/docs/intro.md +0 -46
  28. package/docs/docs/plugins/cookie.md +0 -424
  29. package/docs/docs/plugins/cors.md +0 -295
  30. package/docs/docs/plugins/file.md +0 -382
  31. package/docs/docs/plugins/helmet.md +0 -388
  32. package/docs/docs/plugins/json.md +0 -338
  33. package/docs/docs/plugins/log.md +0 -592
  34. package/docs/docs/plugins/overview.md +0 -390
  35. package/docs/docs/plugins/rate-limiter.md +0 -347
  36. package/docs/docs/plugins/static.md +0 -352
  37. package/docs/docs/plugins/swagger.md +0 -411
  38. package/docs/docs/plugins/urlencoded.md +0 -76
  39. package/docs/docs/testing/examples.md +0 -384
  40. package/docs/docs/testing/mock-server.md +0 -311
  41. package/docs/docs/testing/overview.md +0 -76
  42. package/docs/docusaurus.config.ts +0 -144
  43. package/docs/intro.md +0 -78
  44. package/docs/package.json +0 -46
  45. package/docs/sidebars.ts +0 -72
  46. package/docs/static/.nojekyll +0 -0
  47. package/docs/static/img/docusaurus-social-card.jpg +0 -0
  48. package/docs/static/img/docusaurus.png +0 -0
  49. package/docs/static/img/favicon.ico +0 -0
  50. package/docs/static/img/logo.svg +0 -1
  51. package/docs/static/img/undraw_docusaurus_mountain.svg +0 -37
  52. package/docs/static/img/undraw_docusaurus_react.svg +0 -170
  53. package/docs/static/img/undraw_docusaurus_tree.svg +0 -40
  54. package/docs/tsconfig.json +0 -8
  55. package/speed_test.sh +0 -3
  56. package/test/benchmark/index.ts +0 -17
  57. package/test/cli/cli.ts +0 -7
  58. package/test/commands/test.ts +0 -42
  59. package/test/controllers/file_upload.ts +0 -29
  60. package/test/controllers/urlencoded.ts +0 -13
  61. package/test/controllers/users.ts +0 -111
  62. package/test/cron/index.ts +0 -6
  63. package/test/cron/test_cron.ts +0 -8
  64. package/test/cron/test_cron_imported.ts +0 -8
  65. package/test/native_env.ts +0 -16
  66. package/test/resources/test.txt +0 -1
  67. package/test/server/index.ts +0 -3
  68. package/test/server/instance.ts +0 -63
  69. package/test/suite/upload.test.ts +0 -23
  70. package/test/suite/urlencoded.test.ts +0 -23
  71. package/test/suite/users.test.ts +0 -76
  72. package/todo.md +0 -9
  73. package/tsconfig.json +0 -24
  74. package/vitest.config.ts +0 -17
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/decorators/controller/controller.ts","../src/metadata_store.ts","../src/server/router/router.ts","../src/decorators/handlers/del.ts","../src/decorators/handlers/get.ts","../src/decorators/handlers/patch.ts","../src/decorators/handlers/post.ts","../src/decorators/handlers/put.ts","../src/decorators/middleware/middleware.ts","../src/decorators/validation/validate.ts","../src/server/http/request.ts","../src/validator/validator.ts","../src/runtime/native_request.ts","../src/runtime/runtime.ts","../src/runtime/native_file.ts","../src/plugins/static/static.ts","../src/plugins/static/static_constants.ts","../src/runtime/native_cwd.ts","../src/runtime/native_fs.ts","../src/errors/balda_error.ts","../src/errors/route_not_found.ts","../src/errors/error_factory.ts","../src/errors/method_not_allowed.ts","../src/server/http/response.ts","../src/server/server.ts","../src/plugins/cookie/cookie.ts","../src/logger/logger.ts","../src/plugins/log/log.ts","../src/plugins/rate_limiter/in_memory_storage.ts","../src/plugins/rate_limiter/rate_limiter.ts","../src/runtime/native_server/server_utils.ts","../src/plugins/body_parser/body_parser.ts","../src/plugins/cors/cors.ts","../src/plugins/file/file.ts","../src/errors/file_too_large.ts","../src/plugins/helmet/helmet.ts","../src/errors/json_not_valid.ts","../src/plugins/json/json.ts","../src/plugins/swagger/swagger.ts","../src/runtime/native_server/server_bun.ts","../src/runtime/native_server/server_deno.ts","../src/runtime/native_server/server_node.ts","../src/runtime/native_server/server_connector.ts","../src/server/server_constants.ts","../src/mock/mock_response.ts","../src/mock/mock_server.ts","../src/plugins/urlencoded/urlencoded.ts","../src/cron/cron.ts","../src/plugins/base_plugin.ts"],"sourcesContent":["// Decorators\nexport * from \"./decorators/controller/controller\";\nexport * from \"./decorators/handlers/del\";\nexport * from \"./decorators/handlers/get\";\nexport * from \"./decorators/handlers/patch\";\nexport * from \"./decorators/handlers/post\";\nexport * from \"./decorators/handlers/put\";\nexport * from \"./decorators/middleware/middleware\";\nexport * from \"./decorators/validation/validate\";\n\n// Server\nexport * from \"./server/http/next\";\nexport * from \"./server/http/request\";\nexport * from \"./server/http/response\";\nexport * from \"./server/server\";\nexport * from \"./server/server_types\";\n\n// Plugins\nexport * from \"./plugins/cors/cors\";\nexport * from \"./plugins/json/json\";\nexport * from \"./plugins/static/static\";\nexport * from \"./plugins/cookie/cookie\";\nexport * from \"./plugins/base_plugin\";\nexport * from \"./plugins/rate_limiter/rate_limiter\";\nexport * from \"./plugins/log/log\";\nexport * from \"./plugins/file/file\";\nexport * from \"./plugins/helmet/helmet\";\nexport * from \"./plugins/urlencoded/urlencoded\";\n\n// Router\nimport type { ClientRouter } from \"./server/router/router_type\";\nimport { router as routerInstance } from \"./server/router/router\";\n/**\n * Main router instance that handles all route registrations inside the balda server\n */\nexport const router = routerInstance as ClientRouter;\n","import { join } from \"node:path\";\nimport type { HttpMethod } from \"../../runtime/native_server/server_types\";\nimport { MetadataStore } from \"../../metadata_store\";\nimport { router } from \"../../server/router/router\";\nimport { SwaggerRouteOptions } from \"src/plugins/swagger/swagger_types\";\n\n/**\n * Decorator to mark a class as a controller, routes defined in the controller will be registered at import time when calling the `listen` method.\n * You can customize the path pattern for controller imports in the server options `controllerPatterns`\n * @param path - The path pattern for the controller.\n * @param swaggerOptions - The swagger options for the controller that will be applied to all routes defined in the controller. Controller options will override route options.\n * @swagger If swagger is enabled, the default service name for all routes defined in the controller will be the controller name.\n * @swagger For naming commodity, the default service name will remove the \"Controller\" suffix if it exists. e.g. \"UserController\" -> \"User\"\n */\nexport const controller = (\n path?: string,\n swaggerOptions?: SwaggerRouteOptions,\n) => {\n return (target: any) => {\n const classMeta = MetadataStore.get(target.prototype, \"__class__\");\n const classMiddlewares = classMeta?.middlewares || [];\n const metaMap = MetadataStore.getAll(target.prototype);\n for (const [propertyKey, meta] of metaMap.entries()) {\n if (!meta.route) {\n continue;\n }\n\n const handler = target.prototype[propertyKey];\n const fullPath = path ? join(path, meta.route.path) : meta.route.path;\n\n // Prepend class-level middlewares before route-level\n const allMiddlewares = [...classMiddlewares, ...(meta.middlewares || [])];\n router.addOrUpdate(\n meta.route.method as HttpMethod,\n fullPath,\n allMiddlewares,\n handler,\n {\n // default service name\n service: target.name.replace(/Controller$/, \"\"),\n // controller options\n ...swaggerOptions,\n // route options\n ...meta.documentation,\n },\n );\n }\n\n MetadataStore.clear(target.prototype);\n };\n};\n","/**\n * Cross-runtime metadata store used to store metadata for the decorators without using reflect-metadata\n */\nexport class MetadataStore {\n private static metadata = new WeakMap<any, Map<string | symbol, any>>();\n\n /**\n * Set the metadata for the given target and property key\n */\n static set(target: any, propertyKey: string, value: any): void {\n if (!this.metadata.has(target)) {\n this.metadata.set(target, new Map());\n }\n this.metadata.get(target)!.set(propertyKey, value);\n }\n\n /**\n * Get the metadata for the given target and property key\n */\n static get(target: any, propertyKey: string): any {\n return this.metadata.get(target)?.get(propertyKey);\n }\n\n /**\n * Get all the metadata for the given target\n */\n static getAll(target: any): Map<string | symbol, any> {\n return this.metadata.get(target) || new Map();\n }\n\n /**\n * Delete the metadata for the given target and property key\n */\n static delete(target: any, propertyKey: string | symbol): void {\n this.metadata.get(target)?.delete(propertyKey.toString());\n }\n\n /**\n * Clear all the metadata for the given target\n */\n static clear(target: any): void {\n this.metadata.delete(target);\n }\n}\n","import type { Params, Route } from \"./router_type\";\nimport {\n HttpMethod,\n ServerRouteHandler,\n ServerRouteMiddleware,\n} from \"../../runtime/native_server/server_types\";\nimport type { Request } from \"../http/request\";\nimport type { Response } from \"../http/response\";\nimport type { SwaggerRouteOptions } from \"src/plugins/swagger/swagger_types\";\n\nclass Node {\n staticChildren: Map<string, Node>;\n paramChild: { node: Node; name: string } | null;\n wildcardChild: Node | null;\n middleware: ServerRouteMiddleware[] | null;\n handler: ((req: Request, res: Response) => void) | null;\n\n constructor() {\n this.staticChildren = new Map();\n this.paramChild = null;\n this.wildcardChild = null;\n this.middleware = null;\n this.handler = null;\n }\n}\n\n/**\n * Singleton that handles the routing of requests to the appropriate handler(s).\n */\nexport class Router {\n private trees: Map<string, Node>;\n private routes: Route[];\n\n constructor() {\n this.trees = new Map();\n this.routes = [];\n }\n\n getRoutes(): Route[] {\n return this.routes.slice();\n }\n\n addOrUpdate(\n method: HttpMethod,\n path: string,\n middleware: ServerRouteMiddleware[],\n handler: ServerRouteHandler,\n swaggerOptions?: SwaggerRouteOptions,\n ): void {\n method = method.toUpperCase() as HttpMethod;\n\n // ensure root exists\n let root = this.trees.get(method);\n if (!root) {\n root = new Node();\n this.trees.set(method, root);\n }\n\n // strip query string and split into segments\n const clean = path.split(\"?\")[0];\n const segments = clean.replace(/^\\/+|\\/+$/g, \"\").split(\"/\");\n\n let node = root;\n for (const seg of segments) {\n if (seg === \"*\") {\n if (!node.wildcardChild) {\n node.wildcardChild = new Node();\n }\n node = node.wildcardChild;\n break;\n }\n\n if (seg.startsWith(\":\")) {\n const name = seg.slice(1);\n if (!node.paramChild) {\n node.paramChild = { node: new Node(), name };\n }\n node = node.paramChild.node;\n continue;\n }\n\n // static segment\n if (!node.staticChildren.has(seg)) {\n node.staticChildren.set(seg, new Node());\n }\n node = node.staticChildren.get(seg)!;\n }\n\n // assign middleware & handler\n node.middleware = middleware;\n node.handler = handler;\n\n // upsert in registry\n const idx = this.routes.findIndex(\n (r) => r.method === method && r.path === path,\n );\n if (idx !== -1) {\n this.routes[idx].middleware = middleware;\n this.routes[idx].handler = handler;\n return;\n }\n\n this.routes.push({ method, path, middleware, handler, swaggerOptions });\n }\n\n find(\n method: string,\n rawPath: string,\n ): {\n middleware: ServerRouteMiddleware[];\n handler: ServerRouteHandler;\n params: Params;\n } | null {\n method = method.toUpperCase();\n const root = this.trees.get(method);\n if (!root) {\n return null;\n }\n\n const clean = rawPath.split(\"?\")[0];\n const segments = clean.replace(/^\\/+|\\/+$/g, \"\").split(\"/\");\n const params: Params = {};\n\n let node = root;\n for (let i = 0; i < segments.length; i++) {\n const seg = segments[i];\n\n if (node.staticChildren.has(seg)) {\n node = node.staticChildren.get(seg)!;\n continue;\n }\n\n if (node.paramChild) {\n params[node.paramChild.name] = seg;\n node = node.paramChild.node;\n continue;\n }\n\n if (node.wildcardChild) {\n params[\"*\"] = segments.slice(i).join(\"/\");\n node = node.wildcardChild;\n break;\n }\n\n return null;\n }\n\n if (!node.handler || !node.middleware) {\n return null;\n }\n\n return { middleware: node.middleware, handler: node.handler, params };\n }\n\n /**\n * Apply global middlewares to all routes\n * @param middlewares - The middlewares to apply\n * @internal\n */\n applyGlobalMiddlewaresToAllRoutes(\n middlewares: ServerRouteMiddleware[],\n ): void {\n for (const route of this.routes) {\n this.addOrUpdate(\n route.method as HttpMethod,\n route.path,\n [...middlewares, ...(route.middleware || [])],\n route.handler,\n );\n }\n }\n}\n\nexport const router = new Router();\n","import type { SwaggerRouteOptions } from \"src/plugins/swagger/swagger_types\";\nimport { MetadataStore } from \"../../metadata_store\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\n\ntype DelHandler = (req: Request, res: Response, ...args: any[]) => any;\n\n/**\n * Decorator to mark an handler for a DELETE request\n * @param path - The path of the route\n * @param options - The options for the route\n * @warning Must receive the request and response as the first two arguments or it might not work as expected.\n * @example\n * ```ts\n * import { del, controller, Request, Response } from \"balda\";\n *\n * @controller(\"/api\")\n * class MyController {\n * @del(\"/\")\n * async handler(req: Request, res: Response) {\n * // ...\n * }\n * }\n * ```\n */\nexport const del = (path: string, options?: SwaggerRouteOptions) => {\n return <T extends DelHandler>(\n target: any,\n propertyKey: string,\n descriptor: PropertyDescriptor,\n ): TypedPropertyDescriptor<T> => {\n let meta = MetadataStore.get(target, propertyKey);\n if (!meta) {\n meta = { middlewares: [], route: { path, method: \"DELETE\" } };\n }\n\n meta.documentation = {\n ...(meta.documentation || {}),\n name: propertyKey,\n ...options,\n };\n\n meta.route = { path, method: \"DELETE\" };\n MetadataStore.set(target, propertyKey, meta);\n return descriptor;\n };\n};\n","import type { SwaggerRouteOptions } from \"src/plugins/swagger/swagger_types\";\nimport { MetadataStore } from \"../../metadata_store\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\n\ntype GetHandler = (req: Request, res: Response, ...args: any[]) => any;\n\n/**\n * Decorator to mark an handler for a GET request\n * @param path - The path of the route\n * @param options - The options for the route\n * @warning Must receive the request and response as the first two arguments or it might not work as expected.\n * @example\n * ```ts\n * import { get, controller, Request, Response } from \"balda\";\n *\n * @controller(\"/api\")\n * class MyController {\n * @get(\"/\")\n * async handler(req: Request, res: Response) {\n * // ...\n * }\n * }\n * ```\n */\nexport const get = (path: string, options?: SwaggerRouteOptions) => {\n return <T extends GetHandler>(\n target: any,\n propertyKey: string,\n descriptor: PropertyDescriptor,\n ): TypedPropertyDescriptor<T> => {\n let meta = MetadataStore.get(target, propertyKey);\n if (!meta) {\n meta = { middlewares: [], route: { path, method: \"GET\" } };\n }\n\n meta.documentation = {\n ...(meta.documentation || {}),\n name: propertyKey,\n ...options,\n };\n\n meta.route = { path, method: \"GET\" };\n MetadataStore.set(target, propertyKey, meta);\n return descriptor;\n };\n};\n","import type { SwaggerRouteOptions } from \"src/plugins/swagger/swagger_types\";\nimport { MetadataStore } from \"../../metadata_store\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\n\ntype PatchHandler = (req: Request, res: Response, ...args: any[]) => any;\n\n/**\n * Decorator to mark an handler for a PATCH request\n * @param path - The path of the route\n * @param options - The options for the route\n * @warning Must receive the request and response as the first two arguments or it might not work as expected.\n * @example\n * ```ts\n * import { patch, controller, Request, Response } from \"balda\";\n *\n * @controller(\"/api\")\n * class MyController {\n * @patch(\"/\")\n * async handler(req: Request, res: Response) {\n * // ...\n * }\n * }\n * ```\n */\nexport const patch = (path: string, options?: SwaggerRouteOptions) => {\n return <T extends PatchHandler>(\n target: any,\n propertyKey: string,\n descriptor: PropertyDescriptor,\n ): TypedPropertyDescriptor<T> => {\n let meta = MetadataStore.get(target, propertyKey);\n if (!meta) {\n meta = { middlewares: [], route: { path, method: \"PATCH\" } };\n }\n\n meta.documentation = {\n ...(meta.documentation || {}),\n name: propertyKey,\n ...options,\n };\n\n meta.route = { path, method: \"PATCH\" };\n MetadataStore.set(target, propertyKey, meta);\n return descriptor;\n };\n};\n","import type { SwaggerRouteOptions } from \"src/plugins/swagger/swagger_types\";\nimport { MetadataStore } from \"../../metadata_store\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\n\ntype PostHandler = (req: Request, res: Response, ...args: any[]) => any;\n\n/**\n * Decorator to mark an handler for a POST request\n * @param path - The path of the route\n * @param options - The options for the route\n * @warning Must receive the request and response as the first two arguments or it might not work as expected.\n * @example\n * ```ts\n * import { post, controller, Request, Response } from \"balda\";\n *\n * @controller(\"/api\")\n * class MyController {\n * @post(\"/\")\n * async handler(req: Request, res: Response) {\n * // ...\n * }\n * }\n * ```\n */\nexport const post = (path: string, options?: SwaggerRouteOptions) => {\n return <T extends PostHandler>(\n target: any,\n propertyKey: string,\n descriptor: PropertyDescriptor,\n ): TypedPropertyDescriptor<T> => {\n let meta = MetadataStore.get(target, propertyKey);\n if (!meta) {\n meta = { middlewares: [], route: { path, method: \"POST\" } };\n }\n\n meta.documentation = {\n ...(meta.documentation || {}),\n name: propertyKey,\n ...options,\n };\n\n meta.route = { path, method: \"POST\" };\n MetadataStore.set(target, propertyKey, meta);\n return descriptor;\n };\n};\n","import type { SwaggerRouteOptions } from \"src/plugins/swagger/swagger_types\";\nimport { MetadataStore } from \"../../metadata_store\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\n\ntype PutHandler = (req: Request, res: Response, ...args: any[]) => any;\n\n/**\n * Decorator to mark an handler for a PUT request\n * @param path - The path of the route\n * @param options - The options for the route\n * @warning Must receive the request and response as the first two arguments or it might not work as expected.\n * @example\n * ```ts\n * import { put, controller, Request, Response } from \"balda\";\n *\n * @controller(\"/api\")\n * class MyController {\n * @put(\"/\")\n * async handler(req: Request, res: Response) {\n * // ...\n * }\n */\nexport const put = (path: string, options?: SwaggerRouteOptions) => {\n return <T extends PutHandler>(\n target: any,\n propertyKey: string,\n descriptor: PropertyDescriptor,\n ): TypedPropertyDescriptor<T> => {\n let meta = MetadataStore.get(target, propertyKey);\n if (!meta) {\n meta = { middlewares: [], route: { path, method: \"PUT\" } };\n }\n\n meta.documentation = {\n ...(meta.documentation || {}),\n name: propertyKey,\n ...options,\n };\n\n meta.route = { path, method: \"PUT\" };\n MetadataStore.set(target, propertyKey, meta);\n return descriptor;\n };\n};\n","import { MetadataStore } from \"../../metadata_store\";\nimport type { ServerRouteMiddleware } from \"../../runtime/native_server/server_types\";\n\n/**\n * Decorator to mark a middleware for a route or a controller class\n */\nexport const middleware = (\n middleware: ServerRouteMiddleware | ServerRouteMiddleware[],\n) => {\n return (\n target: any,\n propertyKey?: string,\n descriptor?: PropertyDescriptor,\n ) => {\n // Class decorator usage\n if (typeof propertyKey === \"undefined\") {\n let meta = MetadataStore.get(target.prototype, \"__class__\");\n if (!meta) {\n meta = { middlewares: [] };\n }\n\n if (!meta.middlewares) {\n meta.middlewares = [];\n }\n\n if (!middleware) {\n throw new Error(\n `Middleware ${String(\n middleware,\n )} not found, are you sure you defined it before using it?`,\n );\n }\n\n if (!Array.isArray(middleware)) {\n middleware = [middleware];\n }\n\n meta.middlewares.push(...middleware);\n MetadataStore.set(target.prototype, \"__class__\", meta);\n return target;\n }\n\n // Method decorator usage\n let meta = MetadataStore.get(target, propertyKey);\n if (!meta) {\n meta = { middlewares: [] };\n }\n\n if (!meta.middlewares) {\n meta.middlewares = [];\n }\n\n if (!Array.isArray(middleware)) {\n middleware = [middleware];\n }\n\n meta.middlewares.push(...middleware);\n MetadataStore.set(target, propertyKey, meta);\n return descriptor;\n };\n};\n","import type { TSchema } from \"@sinclair/typebox\";\nimport { ValidationError } from \"ajv\";\nimport { MetadataStore } from \"../../metadata_store\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\nimport type {\n CustomValidationError,\n ValidationOptions,\n} from \"./validate_types\";\n\n/**\n * Decorator to validate request data using TypeBox schemas.\n * Each validate method injects a new parameter to the handler function with the validated data. Arguments are injected in the order of the validate methods.\n * Using this decorator will also update the Swagger documentation with the validated schema (except for the .all schema since there is no way to if using query strings or body).\n * @param options - Validation options including body, query, or all schemas\n * @warning If validation fails, a 400 error will be returned with the validation errors to the client.\n * @example\n * ```ts\n * import { validate } from \"src/decorators/validation/validate\";\n * import { controller, post } from \"src/decorators/handlers/post\";\n * import { Request } from \"src/server/http/request\";\n * import { Response } from \"src/server/http/response\";\n * import { Type } from \"@sinclair/typebox\";\n *\n * const PayloadSchema = Type.Object({\n * name: Type.String(),\n * email: Type.String(),\n * });\n *\n * @controller(\"/users\")\n * export class UserController {\n * @post(\"/\")\n * @validate.body(PayloadSchema) // This will also update the Swagger documentation with the validated schemas and will override the existing schemas.\n * async createUser(req: Request, res: Response, payload: Static<typeof PayloadSchema>) {\n * // payload is now validated and typed\n * const { name, email } = payload;\n * }\n * }\n * ```\n */\nconst validateDecorator = (\n options: ValidationOptions & { customError?: CustomValidationError },\n) => {\n return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\n const originalMethod = descriptor.value;\n\n let meta = MetadataStore.get(target, propertyKey);\n if (!meta) {\n meta = { middlewares: [], route: {} };\n }\n\n if (!meta.documentation) {\n meta.documentation = {};\n }\n\n if (options.body) {\n meta.documentation.requestBody = options.body;\n }\n\n if (options.query) {\n meta.documentation.query = options.query;\n }\n\n MetadataStore.set(target, propertyKey, meta);\n\n descriptor.value = async function (...args: any[]) {\n const req = args[0] as Request;\n const res = args[1] as Response;\n\n try {\n let validatedBody: any = undefined;\n let validatedQuery: any = undefined;\n let validatedAll: any = undefined;\n\n if (options.body) {\n validatedBody = req.validate(options.body, options.safe);\n }\n\n if (options.query) {\n validatedQuery = req.validateQuery(options.query, options.safe);\n }\n\n if (options.all) {\n validatedAll = req.validateAll(options.all, options.safe);\n }\n\n const newArgs = [...args];\n if (validatedBody !== undefined) {\n newArgs.push(validatedBody);\n }\n if (validatedQuery !== undefined) {\n newArgs.push(validatedQuery);\n }\n if (validatedAll !== undefined) {\n newArgs.push(validatedAll);\n }\n\n return originalMethod.apply(this, newArgs);\n } catch (error) {\n if (!(error instanceof ValidationError)) {\n throw error;\n }\n\n if (options.customError) {\n return res.status(options.customError.status || 400).json({\n received: req.body,\n schema: options.body,\n error: error.errors,\n });\n }\n\n return res.badRequest(error);\n }\n };\n\n return descriptor;\n };\n};\n\n/**\n * Decorator to validate the query parameters against a TypeBox schema\n * @param schema - The TypeBox schema to validate the query parameters against\n * @returns The decorator function\n */\nvalidateDecorator.query = (\n schema: TSchema,\n customError?: CustomValidationError,\n) => {\n return validateDecorator({ query: schema, customError });\n};\n\n/**\n * Decorator to validate the request body against a TypeBox schema\n * @param schema - The TypeBox schema to validate the request body against\n * @returns The decorator function\n */\nvalidateDecorator.body = (\n schema: TSchema,\n customError?: CustomValidationError,\n) => {\n return validateDecorator({ body: schema, customError });\n};\n\n/**\n * Decorator to validate both the request body and query parameters against a TypeBox schema\n * @param schema - The TypeBox schema to validate both the request body and query parameters against\n * @returns The decorator function\n */\nvalidateDecorator.all = (\n schema: TSchema,\n customError?: CustomValidationError,\n) => {\n return validateDecorator({ all: schema, customError });\n};\n\nexport const validate = validateDecorator;\n","import { type Static, type TSchema, Type } from \"@sinclair/typebox\";\nimport type { FormFile } from \"src/plugins/file/file_types\";\nimport { validateSchema } from \"../../validator/validator\";\nimport { NativeRequest } from \"../../runtime/native_request\";\nimport { randomUUID } from \"node:crypto\";\n\n/**\n * The request object.\n * This is the main object that is passed to the handler function.\n * It contains the request body, query parameters, files, cookies, etc.\n * It also contains the validation methods.\n */\nexport class Request extends NativeRequest {\n static fromRequest(request: Request | NativeRequest): Request {\n return new Request(request.url, {\n method: request.method,\n body: request.body,\n headers: request.headers,\n });\n }\n\n /**\n * Enrich native request with validation methods.\n */\n static enrichRequest(request: Request): Request {\n request.validate = <T extends TSchema>(\n inputSchema: T | ((schema: typeof Type) => T),\n safe: boolean = false,\n ): Static<T> => {\n if (typeof inputSchema === \"function\") {\n inputSchema = inputSchema(Type);\n }\n\n return validateSchema(inputSchema, request.body || {}, safe);\n };\n\n request.validateQuery = <T extends TSchema>(\n inputSchema: T | ((schema: typeof Type) => T),\n safe: boolean = false,\n ): Static<T> => {\n if (typeof inputSchema === \"function\") {\n inputSchema = inputSchema(Type);\n }\n\n return validateSchema(inputSchema, request.query || {}, safe);\n };\n\n request.validateAll = <T extends TSchema>(\n inputSchema: T | ((schema: typeof Type) => T),\n safe: boolean = false,\n ): Static<T> => {\n if (typeof inputSchema === \"function\") {\n inputSchema = inputSchema(Type);\n }\n\n return validateSchema(\n inputSchema,\n {\n ...(request.body ? { body: request.body } : {}),\n ...(request.query ? { query: request.query } : {}),\n },\n safe,\n );\n };\n\n request.file = (fieldName: string) => {\n return request.files.find((file) => file.formName === fieldName) ?? null;\n };\n\n request.cookies = {};\n\n request.cookie = (name: string) => {\n return request.cookies[name];\n };\n\n request.files = [];\n\n return request;\n }\n\n /**\n * The file of the request. Only available for multipart/form-data requests and if the file parser middleware is used.\n */\n file: (fieldName: string) => FormFile | null = (fieldName: string) => {\n return this.files.find((file) => file.formName === fieldName) ?? null;\n };\n\n /**\n * The cookies of the request. Only available if the cookie middleware is used.\n */\n cookies: Record<string, string> = {};\n\n /**\n * The cookie of the request. Only available if the cookie middleware is used.\n */\n cookie: (name: string) => string | undefined = (name: string) => {\n return this.cookies[name];\n };\n\n /**\n * The ip address of the request.\n * Tries to get the ip address from the `x-forwarded-for` header. If not available, it will use the remote address from the request.\n */\n ip?: string;\n\n /**\n * The files of the request. Only available for multipart/form-data requests and if the file parser middleware is used.\n */\n files: FormFile[] = [];\n\n /**\n * The parameters of the request.\n */\n params: Record<string, string> = {};\n\n /**\n * The query parameters of the request.\n */\n query: Record<string, string> = {};\n\n /**\n * The raw body of the request. Only available for POST, PUT, PATCH and DELETE requests.\n */\n declare rawBody?: ArrayBuffer;\n\n declare private _id: string;\n\n /**\n * The id of the request.\n */\n get id(): string {\n if (!this._id) {\n this._id = randomUUID();\n }\n\n return this._id;\n }\n\n /**\n * The parsed body of the request\n */\n override body: any;\n\n /**\n * The validated body of the request.\n * @param inputSchema - The schema to validate the body against.\n * @param safe - If true, the function will return the original body if the validation fails instead of throwing an error.\n */\n validate<T extends TSchema>(\n inputSchema: T | ((schema: typeof Type) => T),\n safe: boolean = false,\n ): Static<T> {\n if (typeof inputSchema === \"function\") {\n inputSchema = inputSchema(Type);\n }\n\n return validateSchema(inputSchema, this.body || {}, safe);\n }\n\n /**\n * Validates the query string of the request.\n */\n validateQuery<T extends TSchema>(\n inputSchema: T | ((schema: typeof Type) => T),\n safe: boolean = false,\n ): Static<T> {\n if (typeof inputSchema === \"function\") {\n inputSchema = inputSchema(Type);\n }\n\n return validateSchema(inputSchema, this.query || {}, safe);\n }\n\n /**\n * Validates the body and query string of the request.\n */\n validateAll<T extends TSchema>(\n inputSchema: T | ((schema: typeof Type) => T),\n safe: boolean = false,\n ): Static<T> {\n if (typeof inputSchema === \"function\") {\n inputSchema = inputSchema(Type);\n }\n\n return validateSchema(\n inputSchema,\n {\n ...(this.body ? { body: this.body } : {}),\n ...(this.query ? { query: this.query } : {}),\n },\n safe,\n );\n }\n}\n","import { type Static, type TSchema } from \"@sinclair/typebox\";\nimport Ajv, { ValidationError } from \"ajv\";\nimport addFormats from \"ajv-formats\";\n\nconst ajv = addFormats(new Ajv(), [\n \"date-time\",\n \"time\",\n \"date\",\n \"email\",\n \"hostname\",\n \"ipv4\",\n \"ipv6\",\n \"uri\",\n \"uri-reference\",\n \"uuid\",\n \"uri-template\",\n \"json-pointer\",\n \"relative-json-pointer\",\n \"regex\",\n \"password\",\n \"binary\",\n \"byte\",\n \"iso-date-time\",\n \"iso-time\",\n]);\n\nexport const validateSchema = <T extends TSchema>(\n inputSchema: T,\n data: object,\n safe: boolean = false,\n): Static<T> => {\n const validate = ajv.compile(inputSchema);\n if (!validate(data)) {\n if (safe) {\n return data;\n }\n\n throw new ValidationError(validate.errors || []);\n }\n\n return data;\n};\n","declare global {\n interface Request {\n params: Record<string, string>;\n query: Record<string, string>;\n }\n}\n\nexport class NativeRequest extends Request {}\n","export type RunTimeType = \"bun\" | \"node\" | \"deno\";\n\nclass RunTime {\n type: RunTimeType;\n\n constructor() {\n this.type = this.getRunTime();\n }\n\n private getRunTime(): RunTimeType {\n if (typeof Bun !== \"undefined\") {\n return \"bun\";\n } else if (typeof Deno !== \"undefined\") {\n return \"deno\";\n } else if (typeof process !== \"undefined\") {\n return \"node\";\n }\n\n throw new Error(\"No environment detected\");\n }\n}\n\nexport const runtime = new RunTime();\n","import { runtime } from \"./runtime\";\nimport fs from \"node:fs/promises\";\n\nclass NativeFile {\n file(path: string): any {\n switch (runtime.type) {\n case \"bun\":\n return Bun.file(path);\n case \"node\":\n return fs.readFile(path);\n case \"deno\":\n return Deno.readFile(path);\n default:\n throw new Error(\"Unsupported runtime\");\n }\n }\n}\n\nexport const nativeFile = new NativeFile();\n","import { extname, join, resolve } from \"node:path\";\nimport { mimeTypes } from \"../../plugins/static/static_constants\";\nimport { nativeCwd } from \"../../runtime/native_cwd\";\nimport { nativeFs } from \"../../runtime/native_fs\";\nimport type { ServerRouteMiddleware } from \"../../runtime/native_server/server_types\";\nimport { router } from \"../../server/router/router\";\nimport type { NextFunction } from \"../../server/http/next\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\nimport { nativeFile } from \"src/runtime/native_file\";\nimport { SwaggerRouteOptions } from \"src/plugins/swagger/swagger_types\";\nimport { RouteNotFoundError } from \"src/errors/route_not_found\";\nimport { errorFactory } from \"src/errors/error_factory\";\nimport { MethodNotAllowedError } from \"src/errors/method_not_allowed\";\n\n/**\n * Creates a static file serving middleware and registers all routes for the given path (path + \"/*\")\n * @param path - The api path to serve static files from.\n * @example 'public' -> localhost:3000/public/index.html will search for public/index.html in the current directory\n */\nexport const serveStatic = (\n path: string = \"public\",\n swaggerOptions?: SwaggerRouteOptions,\n): ServerRouteMiddleware => {\n // Static files handler\n router.addOrUpdate(\n \"GET\",\n `${path}/*`,\n [],\n async (req, res) => {\n return staticFileHandler(req, res, path);\n },\n {\n service: \"StaticFiles\",\n ...swaggerOptions,\n },\n );\n\n return async (_req: Request, _res: Response, next: NextFunction) => {\n return next();\n };\n};\n\nasync function staticFileHandler(req: Request, res: Response, path: string) {\n if (req.method !== \"GET\" && req.method !== \"HEAD\") {\n return res.status(405).json({\n ...errorFactory(new MethodNotAllowedError(req.url, req.method)),\n });\n }\n\n const wildcardPath = req.params[\"*\"] || \"\";\n const filePath = join(path, wildcardPath);\n const resolvedPath = resolve(nativeCwd.getCwd(), filePath);\n\n const stats = await nativeFs.stat(resolvedPath);\n if (!stats.isFile) {\n return res.notFound({\n ...errorFactory(new RouteNotFoundError(req.url, req.method)),\n });\n }\n\n const contentType = getContentType(extname(resolvedPath));\n res.setHeader(\"Content-Type\", contentType);\n const fileContent = await nativeFile.file(resolvedPath);\n res.raw(fileContent);\n}\n\nexport function getContentType(ext: string) {\n return mimeTypes.get(ext) || \"application/octet-stream\";\n}\n","export const mimeTypes = new Map<string, string>([\n [\".html\", \"text/html\"],\n [\".css\", \"text/css\"],\n [\".js\", \"application/javascript\"],\n [\".png\", \"image/png\"],\n [\".jpg\", \"image/jpeg\"],\n [\".gif\", \"image/gif\"],\n [\".svg\", \"image/svg+xml\"],\n [\".json\", \"application/json\"],\n [\".txt\", \"text/plain\"],\n [\".ico\", \"image/x-icon\"],\n [\".webp\", \"image/webp\"],\n [\".mp4\", \"video/mp4\"],\n [\".mp3\", \"audio/mpeg\"],\n [\".wav\", \"audio/wav\"],\n [\".ogg\", \"audio/ogg\"],\n [\".webm\", \"video/webm\"],\n]);\n","import { runtime } from \"./runtime\";\n\nclass NativeCwd {\n getCwd(): string {\n switch (runtime.type) {\n case \"node\":\n case \"bun\":\n return process.cwd();\n case \"deno\":\n return Deno.cwd();\n default:\n throw new Error(\"Unsupported runtime\");\n }\n }\n}\n\nexport const nativeCwd = new NativeCwd();\n","import { runtime } from \"./runtime\";\n\nclass NativeFs {\n async readFile(path: string): Promise<Uint8Array> {\n switch (runtime.type) {\n case \"node\":\n const fs = await import(\"fs/promises\");\n const buffer = await fs.readFile(path);\n return new Uint8Array(buffer);\n case \"bun\":\n const arrayBuffer = await Bun.file(path).arrayBuffer();\n return new Uint8Array(arrayBuffer);\n case \"deno\":\n return new Uint8Array(await Deno.readFile(path));\n }\n }\n\n async writeFile(path: string, data: Uint8Array): Promise<void> {\n switch (runtime.type) {\n case \"node\":\n const fs = await import(\"fs/promises\");\n await fs.writeFile(path, data);\n break;\n case \"bun\":\n await Bun.write(path, data);\n break;\n case \"deno\":\n await Deno.writeFile(path, data);\n break;\n }\n }\n\n async stat(path: string): Promise<{\n isDirectory: boolean;\n isFile: boolean;\n isSymbolicLink: boolean;\n size: number;\n }> {\n switch (runtime.type) {\n case \"node\":\n const fs = await import(\"fs/promises\");\n const stats = await fs.stat(path);\n return {\n isDirectory: stats.isDirectory(),\n isFile: stats.isFile(),\n isSymbolicLink: stats.isSymbolicLink(),\n size: stats.size,\n };\n case \"bun\":\n const bunStats = await Bun.file(path).stat();\n return {\n isDirectory: bunStats.isDirectory(),\n isFile: bunStats.isFile(),\n isSymbolicLink: bunStats.isSymbolicLink(),\n size: bunStats.size,\n };\n case \"deno\":\n const denoStats = await Deno.stat(path);\n return {\n isDirectory: denoStats.isDirectory,\n isFile: denoStats.isFile,\n isSymbolicLink: false,\n size: denoStats.size,\n };\n }\n }\n\n async unlink(path: string): Promise<void> {\n switch (runtime.type) {\n case \"node\":\n const fs = await import(\"fs/promises\");\n await fs.unlink(path);\n break;\n case \"bun\":\n await Bun.file(path).delete();\n break;\n case \"deno\":\n await Deno.remove(path);\n break;\n default:\n throw new Error(\"Unsupported runtime\");\n }\n }\n}\n\nexport const nativeFs = new NativeFs();\n","export class BaldaError extends Error {\n constructor(message: string) {\n super(message);\n }\n}\n","import { BaldaError } from \"src/errors/balda_error\";\n\nexport class RouteNotFoundError extends BaldaError {\n constructor(path: string, method: string) {\n super(`ROUTE_NOT_FOUND: Cannot ${method} ${path}`);\n }\n}\n","import type { BaldaError } from \"src/errors/balda_error\";\n\nexport const errorFactory = (error: BaldaError) => {\n return {\n name: error.constructor.name,\n cause: error.cause,\n message: error.message,\n stack: error.stack,\n };\n};\n","import { BaldaError } from \"src/errors/balda_error\";\n\nexport class MethodNotAllowedError extends BaldaError {\n constructor(path: string, method: string) {\n super(`METHOD_NOT_ALLOWED: Cannot ${method} ${path}`);\n }\n}\n","import { CookieOptions } from \"src/plugins/cookie/cookie_types\";\nimport { NativeResponse } from \"../../runtime/native_response\";\nimport { nativeFile } from \"src/runtime/native_file\";\nimport { getContentType } from \"src/plugins/static/static\";\n\n/**\n * The response object.\n * This is the main object that is passed to the handler function.\n * It contains the response body, status, headers, etc.\n * It also contains the methods to send the response.\n */\nexport class Response {\n /**\n * The status of the response\n */\n responseStatus: number;\n\n /**\n * The headers of the response\n */\n headers: Record<string, string>;\n\n /**\n * The body of the response\n */\n private body: any;\n\n constructor(status: number = 200) {\n this.responseStatus = status;\n this.headers = {};\n }\n\n /**\n * Set a header for the response\n */\n setHeader(key: string, value: string): this {\n this.headers[key] = value;\n return this;\n }\n\n /**\n * Set the status of the response, status defaults to 200\n */\n status(status: number): this {\n this.responseStatus = status;\n return this;\n }\n\n /**\n * Send a response with the given body, tries to determine the content type based on the body type, status defaults to 200\n * @warning If cannot determine the content type, it will be sent as is\n */\n send(body: any): void {\n if (body === null || body === undefined) {\n return this.text(\"\");\n }\n\n if (typeof body === \"string\") {\n return this.text(body);\n }\n\n if (\n typeof body === \"number\" ||\n typeof body === \"boolean\" ||\n typeof body === \"bigint\"\n ) {\n return this.text(String(body));\n }\n\n if (body instanceof Date) {\n return this.text(body.toISOString());\n }\n\n if (body instanceof RegExp) {\n return this.text(body.toString());\n }\n\n if (typeof Buffer !== \"undefined\" && body instanceof Buffer) {\n return this.download(new Uint8Array(body));\n }\n\n if (body instanceof ArrayBuffer || body instanceof Uint8Array) {\n return this.download(new Uint8Array(body));\n }\n\n if (typeof body === \"object\" && body !== null) {\n try {\n return this.json(body);\n } catch (error) {\n return this.text(String(body));\n }\n }\n\n if (typeof body === \"function\") {\n return this.text(body.toString());\n }\n\n if (typeof body === \"symbol\") {\n return this.text(body.toString());\n }\n\n this.body = body;\n }\n\n /**\n * Send a response with the given body without any content type or encoding (as is), status defaults to 200\n */\n raw(body: any): void {\n this.body = body;\n }\n\n /**\n * Send a response with the given text, status defaults to 200\n */\n text(body: string): void {\n this.body = body;\n this.headers = {\n ...this.headers,\n \"Content-Type\": \"text/plain\",\n };\n }\n\n /**\n * Send a response with the given JSON, status defaults to 200\n */\n json<T extends Record<string, unknown> | Array<unknown>>(body: T): void {\n this.body = body;\n this.headers = {\n ...this.headers,\n \"Content-Type\": \"application/json\",\n };\n }\n\n /**\n * Send a response with the given HTML, status defaults to 200\n */\n html(body: string): void {\n this.body = body;\n this.headers = {\n ...this.headers,\n \"Content-Type\": \"text/html\",\n };\n }\n\n /**\n * Send a response with the given XML, status defaults to 200\n */\n xml(body: string): void {\n this.body = body;\n this.headers = {\n ...this.headers,\n \"Content-Type\": \"application/xml\",\n };\n }\n\n /**\n * Send a response with the given binary with Content-Type of application/octet-stream header, status defaults to 200\n */\n download(body: Uint8Array): void {\n this.body = body;\n this.headers = {\n ...this.headers,\n \"Content-Type\": \"application/octet-stream\",\n };\n }\n\n /**\n * Send a response with the given file, status defaults to 200\n */\n file(pathToFile: string): void {\n const mimeType = getContentType(pathToFile);\n const file = nativeFile.file(pathToFile);\n this.headers = {\n ...this.headers,\n \"Content-Type\": mimeType,\n };\n }\n\n /**\n * 2XX Success\n */\n\n /**\n * 200 OK\n */\n ok(body?: any): void {\n this.status(200).send(body);\n }\n\n /**\n * 201 Created\n */\n created(body?: any): void {\n this.status(201).send(body);\n }\n\n /**\n * 202 Accepted\n */\n accepted(body?: any): void {\n this.status(202).send(body);\n }\n\n /**\n * 204 No Content\n */\n noContent(): void {\n this.status(204).send(\"\");\n }\n\n /**\n * 206 Partial Content\n */\n partialContent(body?: any): void {\n this.status(206).send(body);\n }\n\n /**\n * 3XX Redirection\n */\n\n /**\n * 300 Multiple Choices\n */\n multipleChoices(url: string): void {\n this.status(300).setHeader(\"Location\", url);\n }\n\n redirect(url: string): void {\n this.status(302).setHeader(\"Location\", url);\n }\n\n /**\n * 301 Moved Permanently\n */\n movedPermanently(url: string): void {\n this.status(301).setHeader(\"Location\", url);\n }\n\n /**\n * 302 Found (Temporary Redirect)\n */\n found(url: string): void {\n this.status(302).setHeader(\"Location\", url);\n }\n\n /**\n * 303 See Other\n */\n seeOther(url: string): void {\n this.status(303).setHeader(\"Location\", url);\n }\n\n /**\n * 304 Not Modified\n */\n notModified(): void {\n this.status(304).send(\"\");\n }\n\n /**\n * 307 Temporary Redirect\n */\n temporaryRedirect(url: string): void {\n this.status(307).setHeader(\"Location\", url);\n }\n\n /**\n * 308 Permanent Redirect\n */\n permanentRedirect(url: string): void {\n this.status(308).setHeader(\"Location\", url);\n }\n\n /**\n * 4XX Client Errors\n */\n\n /**\n * 400 Bad Request\n */\n badRequest(body?: any): void {\n this.status(400).send(body);\n }\n\n /**\n * 401 Unauthorized\n */\n unauthorized(body?: any): void {\n this.status(401).send(body);\n }\n\n /**\n * 403 Forbidden\n */\n forbidden(body?: any): void {\n this.status(403).send(body);\n }\n\n /**\n * 404 Not Found\n */\n notFound(body?: any): void {\n this.status(404).send(body);\n }\n\n /**\n * 405 Method Not Allowed\n */\n methodNotAllowed(body?: any): void {\n this.status(405).send(body);\n }\n\n /**\n * 406 Not Acceptable\n */\n notAcceptable(body?: any): void {\n this.status(406).send(body);\n }\n\n /**\n * 409 Conflict\n */\n conflict(body?: any): void {\n this.status(409).send(body);\n }\n\n /**\n * 410 Gone\n */\n gone(body?: any): void {\n this.status(410).send(body);\n }\n\n /**\n * 413 Payload Too Large\n */\n payloadTooLarge(body?: any): void {\n this.status(413).send(body);\n }\n\n /**\n * 415 Unsupported Media Type\n */\n unsupportedMediaType(body?: any): void {\n this.status(415).send(body);\n }\n\n /**\n * 422 Unprocessable Entity\n */\n unprocessableEntity(body?: any): void {\n this.status(422).send(body);\n }\n\n /**\n * 429 Too Many Requests\n */\n tooManyRequests(body?: any): void {\n this.status(429).send(body);\n }\n\n /**\n * 5XX Server Errors\n */\n internalServerError(body?: any): void {\n this.status(500).send(body);\n }\n\n /**\n * 501 Not Implemented\n */\n notImplemented(body?: any): void {\n this.status(501).send(body);\n }\n\n /**\n * 502 Bad Gateway\n */\n badGateway(body?: any): void {\n this.status(502).send(body);\n }\n\n /**\n * 503 Service Unavailable\n */\n serviceUnavailable(body?: any): void {\n this.status(503).send(body);\n }\n\n /**\n * 504 Gateway Timeout\n */\n gatewayTimeout(body?: any): void {\n this.status(504).send(body);\n }\n\n /**\n * 505 HTTP Version Not Supported\n */\n httpVersionNotSupported(body?: any): void {\n this.status(505).send(body);\n }\n\n /**\n * Set a cookie for the response, does nothing if the cookie middleware is not registered\n */\n cookie(_name: string, _value: string, _options?: CookieOptions): void {}\n\n /**\n * Clear a cookie for the response, does nothing if the cookie middleware is not registered\n */\n clearCookie(_name: string, _options?: CookieOptions): void {}\n\n /**\n * Get the body of the response\n */\n getBody(): any {\n return this.body;\n }\n}\n","import { glob } from \"glob\";\nimport { join } from \"node:path\";\nimport { cookie } from \"src/plugins/cookie/cookie\";\nimport type { CookieMiddlewareOptions } from \"src/plugins/cookie/cookie_types\";\nimport { log } from \"src/plugins/log/log\";\nimport type { LogOptions } from \"src/plugins/log/log_types\";\nimport { rateLimiter } from \"src/plugins/rate_limiter/rate_limiter\";\nimport type {\n RateLimiterKeyOptions,\n StorageOptions,\n} from \"src/plugins/rate_limiter/rate_limiter_types\";\nimport type { SwaggerRouteOptions } from \"src/plugins/swagger/swagger_types\";\nimport { logger } from \"../logger/logger\";\nimport { bodyParser } from \"../plugins/body_parser/body_parser\";\nimport { cors } from \"../plugins/cors/cors\";\nimport type { CorsOptions } from \"../plugins/cors/cors_types\";\nimport { fileParser } from \"../plugins/file/file\";\nimport type { FilePluginOptions } from \"../plugins/file/file_types\";\nimport { helmet } from \"../plugins/helmet/helmet\";\nimport type { HelmetOptions } from \"../plugins/helmet/helmet_types\";\nimport { json } from \"../plugins/json/json\";\nimport type { JsonOptions } from \"../plugins/json/json_options\";\nimport { serveStatic } from \"../plugins/static/static\";\nimport { swagger } from \"../plugins/swagger/swagger\";\nimport { nativeCwd } from \"../runtime/native_cwd\";\nimport { ServerConnector } from \"../runtime/native_server/server_connector\";\nimport type {\n RuntimeServerMap,\n ServerListenCallback,\n ServerRouteHandler,\n ServerRouteMiddleware,\n ServerTapOptions,\n} from \"../runtime/native_server/server_types\";\nimport { runtime } from \"../runtime/runtime\";\nimport { router } from \"./router/router\";\nimport { PROTECTED_KEYS } from \"./server_constants\";\nimport type {\n ServerErrorHandler,\n ServerInterface,\n ServerOptions,\n ServerPlugin,\n SignalEvent,\n StandardMethodOptions,\n} from \"./server_types\";\nimport { MockServer } from \"src/mock/mock_server\";\nimport { urlencoded } from \"src/plugins/urlencoded/urlencoded\";\nimport type { UrlEncodedOptions } from \"src/plugins/urlencoded/urlencoded_types\";\nimport { RouteNotFoundError } from \"src/errors/route_not_found\";\nimport { errorFactory } from \"src/errors/error_factory\";\nimport { CronService } from \"src/cron/cron\";\n\n/**\n * The server class that is used to create and manage the server\n */\nexport class Server implements ServerInterface {\n isListening: boolean;\n\n private wasInitialized: boolean;\n private serverConnector: ServerConnector;\n private globalMiddlewares: ServerRouteMiddleware[] = [];\n private options: Required<ServerOptions>;\n private controllerImportBlacklistedPaths: string[] = [\"node_modules\"];\n\n /**\n * The constructor for the server\n * @warning Routes will only be defined after calling the `listen` method so you're free to define middlewares before calling it\n * @param options - The options for the server\n * @param options.port - The port to listen on, defaults to 80\n * @param options.host - The hostname to listen on, defaults to 0.0.0.0\n * @param options.controllerPatterns - The patterns to match for controllers, defaults to an empty array\n * @param options.plugins - The plugins to apply to the server, by default no plugins are applied, plugins are applied in the order they are defined in the options\n * @param options.logger - The logger to use for the server, by default a default logger is used\n * @param options.tapOptions - Options fetch to the runtime server before the server is up and running\n */\n constructor(options?: ServerOptions) {\n this.wasInitialized = false;\n this.options = {\n port: options?.port ?? 80,\n host: options?.host ?? \"0.0.0.0\",\n controllerPatterns: options?.controllerPatterns ?? [],\n plugins: options?.plugins ?? {},\n tapOptions: options?.tapOptions ?? ({} as ServerTapOptions),\n swagger: options?.swagger ?? true,\n };\n\n this.serverConnector = new ServerConnector({\n routes: [],\n port: this.options.port,\n host: this.options.host,\n tapOptions: this.options.tapOptions,\n runtime: runtime.type,\n });\n\n this.use(bodyParser());\n\n this.isListening = false;\n }\n\n get url(): string {\n return this.serverConnector.url;\n }\n\n get port(): number {\n return this.serverConnector.port;\n }\n\n get host(): string {\n return this.serverConnector.host;\n }\n\n tmpDir(...append: string[]): string {\n const baseTmpDir = \"tmp\";\n if (append) {\n return join(baseTmpDir, ...append);\n }\n\n return join(nativeCwd.getCwd(), baseTmpDir);\n }\n\n get(path: string, handler: ServerRouteHandler): void;\n get(\n path: string,\n options: StandardMethodOptions,\n handler: ServerRouteHandler,\n ): void;\n get(\n path: string,\n optionsOrHandler: StandardMethodOptions | ServerRouteHandler,\n maybeHandler?: ServerRouteHandler,\n ): void {\n const { middlewares, handler, swaggerOptions } =\n this.extractOptionsAndHandlerFromRouteRegistration(\n optionsOrHandler,\n maybeHandler,\n );\n\n router.addOrUpdate(\"GET\", path, middlewares, handler, swaggerOptions);\n }\n\n post(path: string, handler: ServerRouteHandler): void;\n post(\n path: string,\n options: StandardMethodOptions,\n handler: ServerRouteHandler,\n ): void;\n post(\n path: string,\n optionsOrHandler: StandardMethodOptions | ServerRouteHandler,\n maybeHandler?: ServerRouteHandler,\n ): void {\n const { middlewares, handler, swaggerOptions } =\n this.extractOptionsAndHandlerFromRouteRegistration(\n optionsOrHandler,\n maybeHandler,\n );\n\n router.addOrUpdate(\"POST\", path, middlewares, handler, swaggerOptions);\n }\n\n patch(path: string, handler: ServerRouteHandler): void;\n patch(\n path: string,\n options: StandardMethodOptions,\n handler: ServerRouteHandler,\n ): void;\n patch(\n path: string,\n optionsOrHandler: StandardMethodOptions | ServerRouteHandler,\n maybeHandler?: ServerRouteHandler,\n ): void {\n const { middlewares, handler, swaggerOptions } =\n this.extractOptionsAndHandlerFromRouteRegistration(\n optionsOrHandler,\n maybeHandler,\n );\n\n router.addOrUpdate(\"PATCH\", path, middlewares, handler, swaggerOptions);\n }\n\n put(path: string, handler: ServerRouteHandler): void;\n put(\n path: string,\n options: StandardMethodOptions,\n handler: ServerRouteHandler,\n ): void;\n put(\n path: string,\n optionsOrHandler: StandardMethodOptions | ServerRouteHandler,\n maybeHandler?: ServerRouteHandler,\n ): void {\n const { middlewares, handler, swaggerOptions } =\n this.extractOptionsAndHandlerFromRouteRegistration(\n optionsOrHandler,\n maybeHandler,\n );\n\n router.addOrUpdate(\"PUT\", path, middlewares, handler, swaggerOptions);\n }\n\n delete(path: string, handler: ServerRouteHandler): void;\n delete(\n path: string,\n options: StandardMethodOptions,\n handler: ServerRouteHandler,\n ): void;\n delete(\n path: string,\n optionsOrHandler: StandardMethodOptions | ServerRouteHandler,\n maybeHandler?: ServerRouteHandler,\n ): void {\n const { middlewares, handler, swaggerOptions } =\n this.extractOptionsAndHandlerFromRouteRegistration(\n optionsOrHandler,\n maybeHandler,\n );\n\n router.addOrUpdate(\"DELETE\", path, middlewares, handler, swaggerOptions);\n }\n\n getNodeServer(): RuntimeServerMap<\"node\"> {\n if (runtime.type !== \"node\") {\n throw new Error(\n \"Server is not using node runtime, you can't call `.getNodeServer()`\",\n );\n }\n\n return this.serverConnector.getServer(\"node\");\n }\n\n embed(key: string, value: any): void {\n if (typeof key !== \"string\" || key.trim() === \"\") {\n throw new Error(\n `Invalid key provided to embed: ${key}. Key must be a non-empty string.`,\n );\n }\n\n if (PROTECTED_KEYS.includes(key)) {\n throw new Error(\n `Cannot embed value with key '${key}' as it conflicts with a protected server property.`,\n );\n }\n\n Object.defineProperty(this, key, {\n value,\n writable: false,\n configurable: true,\n enumerable: true,\n });\n }\n\n exit(code: number = 0): void {\n switch (runtime.type) {\n case \"bun\":\n case \"node\":\n process.exit(code);\n case \"deno\":\n Deno.exit(code);\n default:\n throw new Error(`Unsupported runtime: ${runtime.type}`);\n }\n }\n\n on(event: SignalEvent, cb: () => void): void;\n on(event: string, cb: () => void): void;\n on(event: SignalEvent | string, cb: () => void): void {\n switch (runtime.type) {\n case \"bun\":\n case \"node\":\n process.on(event, cb);\n break;\n case \"deno\":\n Deno.addSignalListener(event as Deno.Signal, cb);\n break;\n default:\n throw new Error(\n `Unsupported runtime: ${runtime.type}, only node, bun and deno are supported`,\n );\n }\n }\n\n use(...middlewares: ServerRouteMiddleware[]): void {\n this.globalMiddlewares.push(...middlewares);\n }\n\n setErrorHandler(errorHandler?: ServerErrorHandler): void {\n this.globalMiddlewares.unshift(async (req, res, next) => {\n try {\n await next();\n } catch (error) {\n await errorHandler?.(req, res, next, error as Error);\n }\n });\n }\n\n setGlobalCronErrorHandler(\n globalErrorHandler: (\n ...args: Parameters<(typeof CronService)[\"globalErrorHandler\"]>\n ) => void,\n ): void {\n CronService.globalErrorHandler = globalErrorHandler;\n }\n\n startRegisteredCrons = async (\n cronJobPatterns?: string[],\n onStart?: () => void,\n ) => {\n if (cronJobPatterns?.length) {\n await CronService.massiveImportCronJobs(cronJobPatterns);\n }\n\n CronService.run().then(() => {\n onStart?.();\n });\n };\n\n listen(cb?: ServerListenCallback): void {\n if (this.isListening) {\n throw new Error(\n \"Server is already listening, you can't call `.listen()` multiple times\",\n );\n }\n\n this.bootstrap().then(() => {\n this.serverConnector.listen();\n this.isListening = true;\n if (this.options.swagger) {\n swagger(this.options.swagger);\n }\n\n cb?.({\n port: this.port,\n host: this.host,\n url: this.url,\n });\n });\n }\n\n async close(): Promise<void> {\n await this.serverConnector.close();\n this.isListening = false;\n }\n\n /**\n * Returns a mock server instance that can be used to test the server without starting it\n * It will import the controllers and apply the plugins to the mock server\n */\n async getMockServer(): Promise<MockServer> {\n await this.bootstrap();\n return new MockServer(this);\n }\n\n private async importControllers(): Promise<void> {\n const controllerPatterns = this.options.controllerPatterns;\n let controllerPaths = await Promise.all(\n controllerPatterns.map(async (pattern) => {\n return glob(pattern, {\n cwd: nativeCwd.getCwd(),\n });\n }),\n ).then((paths) => paths.flat());\n\n controllerPaths = controllerPaths.flat();\n controllerPaths = controllerPaths.filter(\n (path) =>\n !this.controllerImportBlacklistedPaths.some((blacklistedPath) =>\n path.includes(blacklistedPath),\n ),\n );\n\n logger.debug(`Found ${controllerPaths.length} controllers to import`);\n await Promise.all(\n controllerPaths.map(async (controllerPath) => {\n logger.debug(`Importing controller ${controllerPath}`);\n await import(controllerPath).catch((err) => {\n logger.error(`Error importing controller ${controllerPath}: ${err}`);\n });\n }),\n );\n }\n\n private extractOptionsAndHandlerFromRouteRegistration(\n optionsOrHandler: StandardMethodOptions | ServerRouteHandler,\n maybeHandler?: ServerRouteHandler,\n ): {\n middlewares: ServerRouteMiddleware[];\n handler: ServerRouteHandler;\n swaggerOptions?: SwaggerRouteOptions;\n } {\n if (typeof optionsOrHandler === \"function\") {\n // Handler only\n return {\n middlewares: [],\n handler: optionsOrHandler as ServerRouteHandler,\n swaggerOptions: undefined,\n };\n }\n\n // StandardMethodOptions\n const options = optionsOrHandler as StandardMethodOptions;\n const middlewares = Array.isArray(options.middlewares)\n ? options.middlewares\n : options.middlewares\n ? [options.middlewares]\n : [];\n\n return {\n middlewares,\n handler: maybeHandler!,\n swaggerOptions: options.swagger,\n };\n }\n\n private applyPlugins(plugins: ServerPlugin): void {\n Object.entries(plugins).forEach(([pluginName, pluginOptions]) => {\n switch (pluginName as keyof ServerPlugin) {\n case \"cors\":\n this.use(cors(pluginOptions as CorsOptions));\n break;\n case \"json\":\n this.use(json(pluginOptions as JsonOptions));\n break;\n case \"static\":\n this.use(serveStatic(pluginOptions as string));\n break;\n case \"fileParser\":\n this.use(fileParser(pluginOptions as FilePluginOptions));\n break;\n case \"helmet\":\n this.use(helmet(pluginOptions as HelmetOptions));\n break;\n case \"cookie\":\n this.use(cookie(pluginOptions as CookieMiddlewareOptions));\n break;\n case \"log\":\n this.use(log(pluginOptions as LogOptions));\n break;\n case \"rateLimiter\":\n const { keyOptions, storageOptions } = pluginOptions as {\n keyOptions?: RateLimiterKeyOptions;\n storageOptions?: StorageOptions;\n };\n\n this.use(rateLimiter(keyOptions, storageOptions));\n break;\n case \"urlencoded\":\n this.use(urlencoded(pluginOptions as UrlEncodedOptions));\n break;\n default:\n logger.warn(`Unknown plugin ${pluginName}`);\n break;\n }\n });\n }\n\n /**\n * Initializes the server by importing the controllers and applying the plugins, it's idempotent, it will not re-import the controllers or apply the plugins if the server was already initialized (e.g. mockServer init)\n * @internal\n */\n private async bootstrap(): Promise<void> {\n if (this.wasInitialized) {\n return;\n }\n\n await this.importControllers();\n this.applyPlugins(this.options.plugins);\n this.registerNotFoundRoutes();\n if (this.globalMiddlewares.length) {\n router.applyGlobalMiddlewaresToAllRoutes(this.globalMiddlewares);\n }\n\n this.wasInitialized = true;\n }\n\n /**\n * Registers a not found route for all routes that are not defined\n * @internal\n */\n private registerNotFoundRoutes(): void {\n router.addOrUpdate(\n \"GET\",\n \"*\",\n [],\n (req, res) => {\n const notFoundError = new RouteNotFoundError(req.url, req.method);\n res.notFound({\n ...errorFactory(notFoundError),\n });\n },\n {\n excludeFromSwagger: true,\n },\n );\n\n router.addOrUpdate(\n \"POST\",\n \"*\",\n [],\n (req, res) => {\n const notFoundError = new RouteNotFoundError(req.url, req.method);\n res.notFound({\n ...errorFactory(notFoundError),\n });\n },\n {\n excludeFromSwagger: true,\n },\n );\n\n router.addOrUpdate(\n \"PUT\",\n \"*\",\n [],\n (req, res) => {\n const notFoundError = new RouteNotFoundError(req.url, req.method);\n res.notFound({\n ...errorFactory(notFoundError),\n });\n },\n {\n excludeFromSwagger: true,\n },\n );\n\n router.addOrUpdate(\n \"PATCH\",\n \"*\",\n [],\n (req, res) => {\n const notFoundError = new RouteNotFoundError(req.url, req.method);\n res.notFound({\n ...errorFactory(notFoundError),\n });\n },\n {\n excludeFromSwagger: true,\n },\n );\n\n router.addOrUpdate(\n \"DELETE\",\n \"*\",\n [],\n (req, res) => {\n const notFoundError = new RouteNotFoundError(req.url, req.method);\n res.notFound({\n ...errorFactory(notFoundError),\n });\n },\n {\n excludeFromSwagger: true,\n },\n );\n }\n}\n","import type { ServerRouteMiddleware } from \"../../runtime/native_server/server_types\";\nimport type { NextFunction } from \"../../server/http/next\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\nimport type { CookieMiddlewareOptions, CookieOptions } from \"./cookie_types\";\n\n/**\n * Cookie middleware for parsing and setting cookies, must be used in order to use the cookie methods on the request and response objects\n * @param options Cookie middleware options\n */\nexport const cookie = (\n options?: CookieMiddlewareOptions,\n): ServerRouteMiddleware => {\n const opts: Required<CookieMiddlewareOptions> = {\n secret: options?.secret ?? \"\",\n defaults: {\n path: \"/\",\n httpOnly: true,\n secure: false,\n sameSite: \"Lax\",\n ...options?.defaults,\n },\n parse: options?.parse ?? true,\n sign: options?.sign ?? false,\n };\n\n return async (req: Request, res: Response, next: NextFunction) => {\n if (opts.parse) {\n const rawCookies = parseCookies(req.headers.get(\"cookie\") || \"\");\n req.cookies = {};\n\n for (const [name, value] of Object.entries(rawCookies)) {\n if (opts.sign && opts.secret) {\n const verified = verifySignedCookie(value, opts.secret);\n if (verified !== false) {\n req.cookies[name] = verified;\n }\n continue;\n }\n\n req.cookies[name] = value;\n }\n }\n\n // Add cookie methods to response\n res.cookie = (\n name: string,\n value: string,\n cookieOptions?: CookieOptions,\n ) => {\n setCookie(res, name, value, { ...opts.defaults, ...cookieOptions }, opts);\n };\n\n res.clearCookie = (name: string, cookieOptions?: CookieOptions) => {\n clearCookie(res, name, { ...opts.defaults, ...cookieOptions });\n };\n\n await next();\n };\n};\n\n/**\n * Parse cookie string into an object\n */\nfunction parseCookies(cookieString: string): Record<string, string> {\n const cookies: Record<string, string> = {};\n\n if (!cookieString) return cookies;\n\n const pairs = cookieString.split(\";\");\n\n for (const pair of pairs) {\n const [name, value] = pair.trim().split(\"=\");\n if (name && value) {\n cookies[decodeURIComponent(name)] = decodeURIComponent(value);\n }\n }\n\n return cookies;\n}\n\n/**\n * Set a cookie on the response\n */\nfunction setCookie(\n res: Response,\n name: string,\n value: string,\n options: CookieOptions,\n middlewareOptions: Required<CookieMiddlewareOptions>,\n): void {\n let cookieValue = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n\n // Add domain\n if (options.domain) {\n cookieValue += `; Domain=${options.domain}`;\n }\n\n // Add path\n if (options.path) {\n cookieValue += `; Path=${options.path}`;\n }\n\n // Add expires\n if (options.expires) {\n cookieValue += `; Expires=${options.expires.toUTCString()}`;\n }\n\n // Add maxAge\n if (options.maxAge) {\n cookieValue += `; Max-Age=${options.maxAge}`;\n }\n\n // Add secure\n if (options.secure) {\n cookieValue += \"; Secure\";\n }\n\n // Add httpOnly\n if (options.httpOnly) {\n cookieValue += \"; HttpOnly\";\n }\n\n // Add sameSite\n if (options.sameSite) {\n cookieValue += `; SameSite=${options.sameSite}`;\n }\n\n // Add priority\n if (options.priority) {\n cookieValue += `; Priority=${options.priority}`;\n }\n\n // Sign cookie if enabled\n if (middlewareOptions.sign && middlewareOptions.secret) {\n cookieValue = signCookie(cookieValue, middlewareOptions.secret);\n }\n\n // Set the Set-Cookie header\n const existingCookies = res.headers[\"set-cookie\"] || \"\";\n const newCookies = existingCookies\n ? `${existingCookies}, ${cookieValue}`\n : cookieValue;\n res.setHeader(\"Set-Cookie\", newCookies);\n}\n\n/**\n * Clear a cookie by setting it to expire in the past\n */\nfunction clearCookie(\n res: Response,\n name: string,\n options: CookieOptions,\n): void {\n const clearOptions: CookieOptions = {\n ...options,\n expires: new Date(0),\n maxAge: 0,\n };\n\n setCookie(res, name, \"\", clearOptions, {\n secret: \"\",\n defaults: {},\n parse: true,\n sign: false,\n });\n}\n\n/**\n * Simple cookie signing (in production, use a proper crypto library)\n */\nfunction signCookie(value: string, secret: string): string {\n // This is a simple hash implementation\n // In production, you should use a proper crypto library like crypto-js or Node.js crypto\n let hash = 0;\n for (let i = 0; i < value.length; i++) {\n const char = value.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash; // Convert to 32-bit integer\n }\n\n const signature = Math.abs(hash).toString(36);\n return `${value}.${signature}`;\n}\n\n/**\n * Verify a signed cookie\n */\nfunction verifySignedCookie(value: string, secret: string): string | false {\n const parts = value.split(\".\");\n if (parts.length !== 2) return false;\n\n const [cookieValue, signature] = parts;\n const expectedSignature = signCookie(cookieValue, secret).split(\".\")[1];\n\n return signature === expectedSignature ? cookieValue : false;\n}\n","import pino from \"pino\";\nimport type { LoggerOptions } from \"./logger_types\";\n\nconst createBaseLogger = () => {\n const baseOptions: LoggerOptions = {\n level: \"info\",\n formatters: {\n level: (label) => {\n return { level: label };\n },\n },\n };\n\n return pino(baseOptions);\n};\n\n/**\n * The logger instance, can be overridden by the `defineLoggerConfig` function\n */\nexport let logger = createBaseLogger();\n\n/**\n * Define the logger config, this will override the logger instance with the given options\n * @param options - The logger options\n */\nexport const defineLoggerConfig = (options?: LoggerOptions) => {\n logger = pino(options);\n};\n","import { logger } from \"src/logger/logger\";\nimport type { LogOptions } from \"src/plugins/log/log_types\";\nimport type { ServerRouteMiddleware } from \"src/runtime/native_server/server_types\";\nimport type { NextFunction } from \"src/server/http/next\";\nimport type { Request } from \"src/server/http/request\";\nimport type { Response } from \"src/server/http/response\";\n\n/**\n * Logs the request and response of the handler, can be set both on a specific route or on a global middleware.\n * @warning Only json objects and strings are logged from the request and response.\n */\nexport const log = (options?: LogOptions): ServerRouteMiddleware => {\n return async (req: Request, res: Response, next: NextFunction) => {\n try {\n const body = req.body;\n if (options?.logRequest ?? true) {\n logger.info({\n type: \"request\",\n requestId: req.id,\n method:\n (options?.requestPayload?.method ?? true) ? req.method : undefined,\n url: (options?.requestPayload?.url ?? true) ? req.url : undefined,\n ip: (options?.requestPayload?.ip ?? true) ? req.ip : undefined,\n headers:\n (options?.requestPayload?.headers ?? true)\n ? req.headers\n : undefined,\n body:\n (options?.requestPayload?.body ?? false)\n ? returnIfObjectOrString(body)\n : undefined,\n });\n }\n\n await next();\n\n if (options?.logResponse ?? true) {\n logger.info({\n type: \"response\",\n requestId: req.id,\n status: options?.responsePayload?.status ?? res.responseStatus,\n body:\n (options?.responsePayload?.body ?? false)\n ? returnIfObjectOrString(res.getBody())\n : undefined,\n headers:\n (options?.responsePayload?.headers ?? false)\n ? res.headers\n : undefined,\n });\n }\n } catch (error) {\n logger.error(error);\n throw error;\n }\n };\n};\n\nfunction returnIfObjectOrString(value: any): any {\n if (typeof value === \"string\") {\n return value;\n }\n\n // must be Record<string, any> in order to be logged as json\n if (value && typeof value === \"object\" && value.constructor === Object) {\n return value;\n }\n\n return;\n}\n","export interface InMemoryStorageInterface {\n get: (key: string) => Promise<number>;\n set: (key: string, value: number) => Promise<void>;\n}\n\nexport class InMemoryStorage implements InMemoryStorageInterface {\n private storage: Map<string, number> = new Map();\n private windowMs: number;\n\n constructor(windowMs: number) {\n this.windowMs = windowMs;\n }\n\n async set(key: string, value: number): Promise<void> {\n this.storage.set(key, value);\n setTimeout(() => {\n this.storage.delete(key);\n }, this.windowMs);\n }\n\n async get(key: string): Promise<number> {\n const entry = this.storage.get(key);\n if (!entry) {\n return 0;\n }\n\n return entry;\n }\n\n protected async delete(key: string): Promise<void> {\n this.storage.delete(key);\n }\n}\n","import {\n InMemoryStorage,\n InMemoryStorageInterface,\n} from \"src/plugins/rate_limiter/in_memory_storage\";\nimport type { ServerRouteMiddleware } from \"../../runtime/native_server/server_types\";\nimport type { NextFunction } from \"../../server/http/next\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\nimport type {\n RateLimiterKeyOptions,\n StorageOptions,\n} from \"./rate_limiter_types\";\n\n/**\n * Rate limiter plugin\n * Rate limiter is a plugin that limits the number of requests to a resource.\n * It can be used to protect a resource from abuse.\n * @param keyOptions Rate limiter key options, tells the middleware how to retrieve the key from the request in to discriminate what to rate limit (all optional, defaults to ip)\n * @param storageOptions Rate limiter storage options, tells the middleware how to store the rate limit data (all optional, defaults to memory)\n */\nexport const rateLimiter = (\n keyOptions?: RateLimiterKeyOptions,\n storageOptions?: StorageOptions,\n): ServerRouteMiddleware => {\n const baseKeyOptions: RateLimiterKeyOptions = {\n type: \"ip\",\n limit: 100,\n message: \"ERR_RATE_LIMIT_EXCEEDED\",\n statusCode: 429,\n ...keyOptions,\n };\n\n const baseStorageOptions: StorageOptions = {\n type: \"memory\",\n ...storageOptions,\n };\n\n if (baseStorageOptions.type === \"memory\" && !baseStorageOptions.windowMs) {\n baseStorageOptions.windowMs = 60000;\n }\n\n const storage: InMemoryStorageInterface =\n baseStorageOptions.type === \"memory\"\n ? new InMemoryStorage(baseStorageOptions.windowMs!)\n : {\n get: baseStorageOptions.get,\n set: baseStorageOptions.set,\n };\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const key = baseKeyOptions.type === \"ip\" ? req.ip : baseKeyOptions.key(req);\n const value = await storage.get(key!);\n if (value >= baseKeyOptions.limit!) {\n return res.status(baseKeyOptions.statusCode!).json({\n message: baseKeyOptions.message,\n });\n }\n\n await storage.set(key!, value + 1);\n return next();\n };\n};\n","import type { Request } from \"../../server/http/request\";\nimport { Response } from \"../../server/http/response\";\nimport type { ServerRouteHandler, ServerRouteMiddleware } from \"./server_types\";\n\n/**\n * Execute a middleware chain\n */\nexport const executeMiddlewareChain = async (\n middlewares: ServerRouteMiddleware[],\n handler: ServerRouteHandler,\n req: Request,\n res: Response = new Response(),\n): Promise<Response> => {\n let currentIndex = 0;\n if (!middlewares.length) {\n await handler(req, res);\n return res;\n }\n\n const next = async (): Promise<void> => {\n currentIndex++;\n\n if (currentIndex >= middlewares.length) {\n await handler(req, res);\n return;\n }\n\n const middleware = middlewares[currentIndex];\n await middleware(req, res, next);\n };\n\n const firstMiddleware = middlewares[0];\n await firstMiddleware(req, res, next);\n\n return res;\n};\n\nexport const canHaveBody = (method?: string) => {\n if (!method) {\n return true;\n }\n\n return [\"post\", \"put\", \"patch\", \"delete\"].includes(method.toLowerCase());\n};\n","import type { ServerRouteMiddleware } from \"../../runtime/native_server/server_types\";\nimport { canHaveBody } from \"../../runtime/native_server/server_utils\";\nimport type { NextFunction } from \"../../server/http/next\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\n\n/**\n * Middleware to parse the body of the request. GET, DELETE and OPTIONS requests are not parsed. Used internally by the server. Will always be applied.\n * @internal\n */\nexport const bodyParser = (): ServerRouteMiddleware => {\n return async (req: Request, _res: Response, next: NextFunction) => {\n if (!canHaveBody(req.method)) {\n return next();\n }\n\n req.rawBody = await req.arrayBuffer();\n Object.defineProperty(req, \"body\", {\n value: undefined,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n\n return next();\n };\n};\n","import type { ServerRouteMiddleware } from \"../../runtime/native_server/server_types\";\nimport type { NextFunction } from \"../../server/http/next\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\nimport type { CorsOptions } from \"./cors_types\";\n\n/**\n * CORS plugin\n * @param options CORS options (all optional)\n */\nexport const cors = (options?: CorsOptions): ServerRouteMiddleware => {\n const opts: CorsOptions = {\n origin: \"*\",\n methods: [\"GET\", \"HEAD\", \"PUT\", \"PATCH\", \"POST\", \"DELETE\"],\n allowedHeaders: \"\",\n exposedHeaders: \"\",\n credentials: false,\n maxAge: undefined,\n preflightContinue: false,\n optionsSuccessStatus: 204,\n ...options,\n };\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const requestOrigin = req.headers.get(\"origin\") || \"\";\n\n if (req.method === \"OPTIONS\") {\n return handlePreflightRequest(req, res, opts, requestOrigin, next);\n }\n\n handleRegularRequest(req, res, opts, requestOrigin);\n await next();\n };\n};\n\n/**\n * Handle CORS preflight OPTIONS requests\n */\nfunction handlePreflightRequest(\n _req: Request,\n res: Response,\n opts: CorsOptions,\n requestOrigin: string,\n next: NextFunction,\n): void {\n const allowOrigin = determineOrigin(opts, requestOrigin);\n if (!allowOrigin) {\n res.forbidden(\"CORS origin not allowed\");\n return;\n }\n\n // Set CORS headers for preflight\n setCorsHeaders(res, opts, allowOrigin);\n\n // Handle preflight continue option\n if (opts.preflightContinue) {\n next();\n return;\n }\n\n // End preflight request\n res.status(opts.optionsSuccessStatus || 204);\n res.send(\"\");\n}\n\n/**\n * Handle regular CORS requests (non-OPTIONS)\n */\nfunction handleRegularRequest(\n _req: Request,\n res: Response,\n opts: CorsOptions,\n requestOrigin: string,\n): void {\n const allowOrigin = determineOrigin(opts, requestOrigin);\n if (!allowOrigin) {\n return;\n }\n\n setCorsHeaders(res, opts, allowOrigin);\n}\n\n/**\n * Determine if origin is allowed and return the appropriate origin value\n */\nfunction determineOrigin(\n opts: CorsOptions,\n requestOrigin: string,\n): string | false {\n // String origin\n if (typeof opts.origin === \"string\") {\n return opts.origin;\n }\n\n // Array of origins\n if (Array.isArray(opts.origin)) {\n const matchedOrigin = opts.origin.find((origin) =>\n typeof origin === \"string\"\n ? origin === requestOrigin\n : origin instanceof RegExp && origin.test(requestOrigin),\n );\n\n return typeof matchedOrigin === \"string\" ? matchedOrigin : false;\n }\n\n return \"*\";\n}\n\n/**\n * Set all CORS headers on the response\n */\nfunction setCorsHeaders(\n res: Response,\n opts: CorsOptions,\n allowOrigin: string,\n): void {\n res.setHeader(\"Access-Control-Allow-Origin\", allowOrigin);\n\n if (opts.credentials) {\n res.setHeader(\"Access-Control-Allow-Credentials\", \"true\");\n }\n\n if (opts.exposedHeaders && opts.exposedHeaders !== \"\") {\n const exposedHeaders = Array.isArray(opts.exposedHeaders)\n ? opts.exposedHeaders.join(\",\")\n : opts.exposedHeaders;\n res.setHeader(\"Access-Control-Expose-Headers\", exposedHeaders);\n }\n\n if (opts.allowedHeaders && opts.allowedHeaders !== \"\") {\n const allowedHeaders = Array.isArray(opts.allowedHeaders)\n ? opts.allowedHeaders.join(\",\")\n : opts.allowedHeaders;\n res.setHeader(\"Access-Control-Allow-Headers\", allowedHeaders);\n }\n\n const methodsStr = Array.isArray(opts.methods)\n ? opts.methods.join(\",\")\n : opts.methods;\n res.setHeader(\"Access-Control-Allow-Methods\", String(methodsStr || \"\"));\n\n if (typeof opts.maxAge === \"number\") {\n res.setHeader(\"Access-Control-Max-Age\", opts.maxAge.toString());\n }\n}\n","import { tmpdir } from \"node:os\";\nimport { extname, join } from \"node:path\";\nimport type {\n FilePluginOptions,\n FormFile,\n} from \"../../plugins/file/file_types\";\nimport { nativeFs } from \"../../runtime/native_fs\";\nimport type { ServerRouteMiddleware } from \"../../runtime/native_server/server_types\";\nimport type { NextFunction } from \"../../server/http/next\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\nimport { FileTooLargeError } from \"src/errors/file_too_large\";\nimport { errorFactory } from \"src/errors/error_factory\";\n\n/**\n * Middleware to handle multipart/form-data file uploads.\n * - Validates each file against the given `FilePluginOptions` (currently only size limit).\n * - Stores every uploaded file in a runtime-agnostic temporary directory and exposes them via `req.files` & `req.file`.\n * - Cleans the temporary files both after successful handler execution and when an unhandled error bubbles up.\n * - Can be used both as a global middleware to check all incoming requests for files and as a route middleware to check only the files for a specific route\n */\nexport const fileParser = (\n options?: FilePluginOptions,\n): ServerRouteMiddleware => {\n return async (req: Request, res: Response, next: NextFunction) => {\n const tmpPaths: string[] = [];\n try {\n const contentType =\n req.headers.get(\"content-type\") ?? req.headers.get(\"Content-Type\");\n\n if (!contentType || !contentType.startsWith(\"multipart/form-data\")) {\n return next();\n }\n\n if (!req.rawBody) {\n return next();\n }\n\n const boundaryMatch = contentType.match(/boundary=(.*)(;|$)/i);\n if (!boundaryMatch) {\n return next();\n }\n\n const boundary = boundaryMatch[1].replace(/(^\\s*\"?|\"?\\s*$)/g, \"\");\n\n const bodyBuf = new Uint8Array(req.rawBody);\n const boundaryBuf = new TextEncoder().encode(`--${boundary}`);\n const CRLFCRLF = new Uint8Array([13, 10, 13, 10]);\n\n const parts: Array<{ headers: string; data: Uint8Array }> = [];\n\n const indexOfSub = (\n haystack: Uint8Array,\n needle: Uint8Array,\n from: number = 0,\n ): number => {\n outer: for (let i = from; i <= haystack.length - needle.length; i++) {\n for (let j = 0; j < needle.length; j++) {\n if (haystack[i + j] !== needle[j]) continue outer;\n }\n return i;\n }\n\n return -1;\n };\n\n let start = indexOfSub(bodyBuf, boundaryBuf);\n while (start !== -1) {\n start += boundaryBuf.length;\n\n if (bodyBuf[start] === 45 && bodyBuf[start + 1] === 45) {\n break;\n }\n\n if (bodyBuf[start] === 13 && bodyBuf[start + 1] === 10) {\n start += 2;\n }\n\n const headerEnd = indexOfSub(bodyBuf, CRLFCRLF, start);\n if (headerEnd === -1) {\n break;\n }\n\n const headersBuf = bodyBuf.subarray(start, headerEnd);\n const headers = new TextDecoder().decode(headersBuf);\n\n const dataStart = headerEnd + CRLFCRLF.length;\n const nextBoundary = indexOfSub(bodyBuf, boundaryBuf, dataStart);\n if (nextBoundary === -1) {\n break;\n }\n\n let dataEnd = nextBoundary - 1;\n if (bodyBuf[dataEnd] === 10) {\n dataEnd--;\n }\n\n if (bodyBuf[dataEnd] === 13) {\n dataEnd--;\n }\n\n const data = bodyBuf.subarray(dataStart, dataEnd + 1);\n parts.push({ headers, data });\n start = nextBoundary;\n }\n\n const files: FormFile[] = [];\n const fields: Record<string, string> = {};\n\n for (const part of parts) {\n const disposition = part.headers\n .split(\"\\r\\n\")\n .find((h) => h.toLowerCase().startsWith(\"content-disposition:\"));\n\n if (!disposition) {\n continue;\n }\n\n const formNameMatch = disposition.match(/name=\"([^\"]+)\"/);\n if (!formNameMatch) {\n continue;\n }\n const formName = formNameMatch[1];\n\n const filenameMatch = disposition.match(/filename=\"([^\"]*)\"/);\n const originalName = filenameMatch ? filenameMatch[1] : \"\";\n const isFile = Boolean(originalName);\n\n if (isFile) {\n if (options?.maxFileSize && part.data.length > options.maxFileSize) {\n return res.badRequest({\n ...errorFactory(\n new FileTooLargeError(\n originalName,\n part.data.length,\n options.maxFileSize,\n ),\n ),\n });\n }\n\n const contentTypeHeader = part.headers\n .split(\"\\r\\n\")\n .find((h) => h.toLowerCase().startsWith(\"content-type:\"));\n\n const mimeType = contentTypeHeader\n ? contentTypeHeader.split(\":\")[1].trim()\n : \"application/octet-stream\";\n\n const extension = extname(originalName);\n const tmpPath = join(tmpdir(), `${randomString(10)}${extension}`);\n await nativeFs.writeFile(tmpPath, part.data);\n tmpPaths.push(tmpPath);\n\n files.push({\n formName,\n mimeType,\n size: part.data.length,\n tmpPath,\n originalName,\n });\n } else {\n // Field\n fields[formName] = new TextDecoder().decode(part.data);\n }\n }\n\n req.files = files;\n req.body = fields;\n\n await next();\n\n await cleanupTmpFiles(tmpPaths);\n } catch (error) {\n await cleanupTmpFiles(tmpPaths);\n throw error;\n }\n };\n};\n\nasync function cleanupTmpFiles(paths: string[]) {\n await Promise.allSettled(paths.map((path) => nativeFs.unlink(path)));\n}\n\nfunction randomString(length: number) {\n return Math.random()\n .toString(36)\n .substring(2, 2 + length);\n}\n","import { BaldaError } from \"src/errors/balda_error\";\n\nexport class FileTooLargeError extends BaldaError {\n constructor(filename: string, size: number, maxSize: number) {\n super(\n `FILE_TOO_LARGE: \"${filename}\" is too large. Max size is ${maxSize} bytes, but got ${size} bytes`,\n );\n }\n}\n","import { HelmetOptions } from \"src/plugins/helmet/helmet_types\";\nimport type { ServerRouteMiddleware } from \"../../runtime/native_server/server_types\";\nimport type { NextFunction } from \"../../server/http/next\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\n\n/**\n * Sets common HTTP security headers\n * @param options Helmet options (all optional)\n */\nexport const helmet = (options?: HelmetOptions): ServerRouteMiddleware => {\n const opts: Required<HelmetOptions> = {\n dnsPrefetchControl: true,\n frameguard: { action: \"SAMEORIGIN\" },\n hsts: { maxAge: 15552000, includeSubDomains: true, preload: false },\n contentTypeOptions: true,\n ieNoOpen: true,\n xssFilter: true,\n referrerPolicy: \"no-referrer\",\n crossOriginResourcePolicy: \"same-origin\",\n crossOriginOpenerPolicy: \"same-origin\",\n crossOriginEmbedderPolicy: \"require-corp\",\n contentSecurityPolicy: false,\n ...options,\n };\n\n return async (_req: Request, res: Response, next: NextFunction) => {\n // X-DNS-Prefetch-Control\n if (opts.dnsPrefetchControl) {\n res.setHeader(\"X-DNS-Prefetch-Control\", \"off\");\n }\n // X-Frame-Options\n if (opts.frameguard) {\n let action = \"SAMEORIGIN\";\n if (typeof opts.frameguard === \"object\") {\n action = opts.frameguard.action;\n }\n res.setHeader(\"X-Frame-Options\", action);\n }\n // Strict-Transport-Security\n if (opts.hsts) {\n let hstsRaw: Partial<{\n maxAge: number;\n includeSubDomains: boolean;\n preload: boolean;\n }> = {};\n if (typeof opts.hsts === \"object\") {\n hstsRaw = opts.hsts;\n }\n const maxAge = hstsRaw.maxAge !== undefined ? hstsRaw.maxAge : 15552000;\n const includeSubDomains =\n hstsRaw.includeSubDomains !== undefined\n ? hstsRaw.includeSubDomains\n : true;\n const preload = hstsRaw.preload !== undefined ? hstsRaw.preload : false;\n let hstsValue = `max-age=${maxAge}`;\n if (includeSubDomains !== false) {\n hstsValue += \"; includeSubDomains\";\n }\n if (preload) {\n hstsValue += \"; preload\";\n }\n res.setHeader(\"Strict-Transport-Security\", hstsValue);\n }\n // X-Content-Type-Options\n if (opts.contentTypeOptions) {\n res.setHeader(\"X-Content-Type-Options\", \"nosniff\");\n }\n // X-Download-Options\n if (opts.ieNoOpen) {\n res.setHeader(\"X-Download-Options\", \"noopen\");\n }\n // X-XSS-Protection\n if (opts.xssFilter) {\n res.setHeader(\"X-XSS-Protection\", \"0\");\n }\n // Referrer-Policy\n if (opts.referrerPolicy) {\n res.setHeader(\"Referrer-Policy\", opts.referrerPolicy);\n }\n // Cross-Origin-Resource-Policy\n if (opts.crossOriginResourcePolicy) {\n res.setHeader(\n \"Cross-Origin-Resource-Policy\",\n opts.crossOriginResourcePolicy,\n );\n }\n // Cross-Origin-Opener-Policy\n if (opts.crossOriginOpenerPolicy) {\n res.setHeader(\"Cross-Origin-Opener-Policy\", opts.crossOriginOpenerPolicy);\n }\n // Cross-Origin-Embedder-Policy\n if (opts.crossOriginEmbedderPolicy) {\n res.setHeader(\n \"Cross-Origin-Embedder-Policy\",\n opts.crossOriginEmbedderPolicy,\n );\n }\n // Content-Security-Policy\n if (opts.contentSecurityPolicy) {\n res.setHeader(\"Content-Security-Policy\", opts.contentSecurityPolicy);\n }\n\n await next();\n };\n};\n","import { BaldaError } from \"src/errors/balda_error\";\n\nexport class JsonNotValidError extends BaldaError {\n constructor(json: any) {\n super(`JSON_NOT_VALID: \"${JSON.stringify(json)}\" is not a valid JSON`);\n }\n}\n","import { errorFactory } from \"src/errors/error_factory\";\nimport { JsonNotValidError } from \"src/errors/json_not_valid\";\nimport type { ServerRouteMiddleware } from \"../../runtime/native_server/server_types\";\nimport { canHaveBody } from \"../../runtime/native_server/server_utils\";\nimport type { NextFunction } from \"../../server/http/next\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\nimport type { JsonOptions } from \"./json_options\";\n\n/**\n * Middleware to parse the JSON body of the request. GET, DELETE and OPTIONS requests are not parsed.\n * @param options - The options for the JSON middleware.\n */\nexport const json = (options?: JsonOptions): ServerRouteMiddleware => {\n return async (req: Request, res: Response, next: NextFunction) => {\n if (!isJsonRequest(req) || !canHaveBody(req.method)) {\n return next();\n }\n\n const sizeLimit = options?.sizeLimit ?? 5 * 1024 * 1024;\n const arrayBuffer = req.rawBody;\n\n if (!arrayBuffer) {\n if (options?.parseEmptyBodyAsObject) {\n req.body = {};\n }\n\n return next();\n }\n\n const byteLength = arrayBuffer.byteLength;\n if (!byteLength) {\n if (options?.parseEmptyBodyAsObject) {\n req.body = {};\n }\n\n return next();\n }\n\n if (byteLength > sizeLimit) {\n const customErrorMessage = {\n status: 413,\n message: \"ERR_REQUEST_BODY_TOO_LARGE\",\n ...options?.customErrorMessage,\n };\n\n return res.status(customErrorMessage.status).json({\n error: customErrorMessage.message,\n });\n }\n\n try {\n const encoding = options?.encoding ?? \"utf-8\";\n const decodedBody = new TextDecoder(encoding).decode(arrayBuffer);\n req.body = JSON.parse(decodedBody);\n } catch (error) {\n if (error instanceof SyntaxError) {\n return res.badRequest({\n ...errorFactory(new JsonNotValidError(\"Invalid JSON syntax\")),\n });\n }\n\n return res.badRequest({\n ...errorFactory(new JsonNotValidError(\"Invalid request body encoding\")),\n });\n }\n\n await next();\n };\n};\n\nfunction isJsonRequest(req: Request): boolean {\n const contentType = getContentType(req);\n if (!contentType) {\n return false;\n }\n\n const mimeType = parseMimeType(contentType);\n return mimeType === \"application/json\";\n}\n\nfunction getContentType(req: Request): string | null {\n const contentType =\n req.headers.get(\"content-type\") ?? req.headers.get(\"Content-Type\");\n if (!contentType) {\n return null;\n }\n\n if (Array.isArray(contentType)) {\n return contentType[0] || null;\n }\n\n return contentType;\n}\n\nfunction parseMimeType(contentType: string): string {\n const trimmed = contentType.trim();\n const semicolonIndex = trimmed.indexOf(\";\");\n\n if (semicolonIndex === -1) {\n return trimmed.toLowerCase();\n }\n\n return trimmed.substring(0, semicolonIndex).trim().toLowerCase();\n}\n","import { TSchema } from \"@sinclair/typebox/type\";\nimport type {\n SwaggerGlobalOptions,\n SwaggerRouteOptions,\n} from \"../../plugins/swagger/swagger_types\";\nimport { router } from \"../../server/router/router\";\n\n/**\n * Swagger plugin that serves the swagger UI and JSON specification, by default the UI will be available at /docs and the JSON specification at /docs/json\n * @warning The json specification is always available at /${globalOptions.path}/json\n * @internal\n */\nexport const swagger = (\n globalOptions?: SwaggerGlobalOptions | boolean,\n): void => {\n let swaggerOptions: SwaggerGlobalOptions = {\n type: \"standard\",\n path: \"/docs\",\n title: \"Balda API Documentation\",\n description: \"API Documentation from the Balda Framework\",\n version: \"1.0.0\",\n servers: [\"http://localhost\"],\n security: [],\n tags: [],\n components: {},\n securitySchemes: {},\n models: {},\n };\n\n if (typeof globalOptions !== \"boolean\") {\n swaggerOptions = {\n ...swaggerOptions,\n ...globalOptions,\n };\n }\n\n const spec = generateOpenAPISpec(swaggerOptions);\n const uiPath = `${swaggerOptions.path}`;\n const jsonPath = `${uiPath}/json`;\n\n const uiContent =\n swaggerOptions.type === \"redoc\"\n ? generateRedocUI(jsonPath, swaggerOptions)\n : swaggerOptions.type === \"rapidoc\"\n ? generateRapiDocUI(jsonPath, swaggerOptions)\n : generateSwaggerUI(jsonPath, swaggerOptions);\n\n router.addOrUpdate(\"GET\", uiPath, [], (_req, res) => {\n res.html(uiContent);\n });\n\n router.addOrUpdate(\"GET\", jsonPath, [], (_req, res) => {\n res.json(spec);\n });\n};\n\nfunction generateOpenAPISpec(globalOptions: SwaggerGlobalOptions) {\n const routes = router.getRoutes();\n const paths: Record<string, any> = {};\n\n const components = {\n ...globalOptions.components,\n securitySchemes: globalOptions.securitySchemes || {},\n schemas: globalOptions.models\n ? {\n ...(globalOptions.components?.schemas || {}),\n ...globalOptions.models,\n }\n : globalOptions.components?.schemas\n ? { ...globalOptions.components.schemas }\n : undefined,\n };\n\n for (const route of routes) {\n const swaggerOptions: SwaggerRouteOptions | undefined =\n route.swaggerOptions;\n if (swaggerOptions?.excludeFromSwagger) continue;\n\n if (!paths[route.path]) paths[route.path] = {};\n const method = route.method.toLowerCase();\n const operation: any = {\n summary: swaggerOptions?.name || `${method.toUpperCase()} ${route.path}`,\n description: swaggerOptions?.description || \"\",\n tags: swaggerOptions?.service ? [swaggerOptions.service] : [],\n deprecated: swaggerOptions?.deprecated || false,\n };\n\n let parameters: any[] = [];\n if (swaggerOptions?.query) {\n if (\n swaggerOptions.query.type === \"object\" &&\n swaggerOptions.query.properties\n ) {\n for (const [name, schema] of Object.entries(\n swaggerOptions.query.properties,\n )) {\n parameters.push({\n name,\n in: \"query\",\n required: Array.isArray(swaggerOptions.query.required)\n ? swaggerOptions.query.required.includes(name)\n : false,\n schema: typeboxToOpenAPI(schema as TSchema),\n });\n }\n }\n }\n if (swaggerOptions && (swaggerOptions as any).params) {\n parameters = parameters.concat(\n extractPathParams(route.path, (swaggerOptions as any).params),\n );\n } else {\n parameters = parameters.concat(extractPathParams(route.path));\n }\n\n if (parameters.length > 0) {\n operation.parameters = parameters;\n }\n\n if (swaggerOptions?.requestBody) {\n let routeBodyContentType = \"application/json\";\n if (swaggerOptions.bodyType === \"form-data\") {\n routeBodyContentType = \"multipart/form-data\";\n } else if (swaggerOptions.bodyType === \"urlencoded\") {\n routeBodyContentType = \"application/x-www-form-urlencoded\";\n }\n operation.requestBody = {\n content: {\n [routeBodyContentType]: {\n schema: typeboxToOpenAPI(swaggerOptions.requestBody),\n },\n },\n required: true,\n };\n } else if (\n swaggerOptions?.bodyType &&\n (swaggerOptions.bodyType.includes(\"form-data\") ||\n swaggerOptions.bodyType.includes(\"urlencoded\"))\n ) {\n operation.requestBody = {\n content: {\n [swaggerOptions.bodyType]: {\n schema: { type: \"object\" },\n },\n },\n required: true,\n };\n }\n\n operation.responses = {};\n if (swaggerOptions?.responses) {\n for (const [statusCode, schema] of Object.entries(\n swaggerOptions.responses,\n )) {\n operation.responses[statusCode] = {\n description: `Response for ${statusCode}`,\n content: {\n \"application/json\": {\n schema: typeboxToOpenAPI(schema as TSchema),\n },\n },\n };\n }\n }\n if (swaggerOptions?.errors) {\n for (const [statusCode, schema] of Object.entries(\n swaggerOptions.errors,\n )) {\n operation.responses[statusCode] = {\n description: `Error response for ${statusCode}`,\n content: {\n \"application/json\": {\n schema: typeboxToOpenAPI(schema as TSchema),\n },\n },\n };\n }\n }\n\n if (Object.keys(operation.responses).length === 0) {\n operation.responses[\"200\"] = {\n description: \"Successful response\",\n content: {\n \"application/json\": {\n schema: { type: \"object\" },\n },\n },\n };\n }\n\n // First we try route specific security\n if (swaggerOptions?.security) {\n const securityArr: any[] = [];\n if (!Array.isArray(swaggerOptions.security)) {\n swaggerOptions.security = [swaggerOptions.security];\n }\n\n for (const sec of swaggerOptions.security) {\n if (sec.type === \"bearer\") {\n if (!components.securitySchemes.bearer) {\n components.securitySchemes.bearer = {\n type: \"http\",\n scheme: \"bearer\",\n bearerFormat: sec.bearerFormat || \"JWT\",\n description: sec.description,\n } as any;\n }\n securityArr.push({ bearer: [] });\n } else if (sec.type === \"apiKey\") {\n // Use sec.name as the scheme name\n if (!components.securitySchemes[sec.name]) {\n components.securitySchemes[sec.name] = {\n type: \"apiKey\",\n name: sec.name,\n in: sec.in,\n description: sec.description,\n };\n }\n securityArr.push({ [sec.name]: [] });\n } else if (sec.type === \"oauth2\") {\n const schemeName = sec.name || \"oauth2\";\n if (!components.securitySchemes[schemeName]) {\n components.securitySchemes[schemeName] = {\n type: \"oauth2\",\n flows: sec.flows,\n description: sec.description,\n };\n }\n securityArr.push({ [schemeName]: [] });\n } else if (sec.type === \"openIdConnect\") {\n const schemeName = sec.name || \"openIdConnect\";\n if (!components.securitySchemes[schemeName]) {\n components.securitySchemes[schemeName] = {\n type: \"openIdConnect\",\n openIdConnectUrl: sec.openIdConnectUrl,\n description: sec.description,\n };\n }\n securityArr.push({ [schemeName]: [] });\n }\n }\n if (securityArr.length) operation.security = securityArr;\n } else if (globalOptions.security) {\n // If no route specific security, we use the global security\n operation.security = globalOptions.security;\n }\n\n paths[route.path][method] = operation;\n }\n\n return {\n openapi: \"3.0.0\",\n info: {\n title: globalOptions.title,\n description: globalOptions.description,\n version: globalOptions.version,\n ...globalOptions.info,\n },\n servers: globalOptions.servers?.map((url) => ({ url })) || [{ url: \"/\" }],\n paths,\n components,\n security: globalOptions.security || [],\n tags: globalOptions.tags\n ? Object.entries(globalOptions.tags).map(([name, config]) => ({\n name,\n ...config,\n }))\n : [],\n };\n}\n\nfunction generateSwaggerUI(\n specUrl: string,\n globalOptions: SwaggerGlobalOptions,\n) {\n return `\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <meta name=\"description\" content=\"${globalOptions.description}\" />\n <title>${globalOptions.title}</title>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui.css\" />\n <style>\n html {\n box-sizing: border-box;\n overflow: -moz-scrollbars-vertical;\n overflow-y: scroll;\n }\n *, *:before, *:after {\n box-sizing: inherit;\n }\n body {\n margin:0;\n background: #fafafa;\n }\n </style>\n</head>\n<body>\n <div id=\"swagger-ui\"></div>\n <script src=\"https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-bundle.js\"></script>\n <script src=\"https://unpkg.com/swagger-ui-dist@5.9.0/swagger-ui-standalone-preset.js\"></script>\n <script>\n window.onload = function() {\n const ui = SwaggerUIBundle({\n url: '${specUrl}',\n dom_id: '#swagger-ui',\n deepLinking: true,\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIStandalonePreset\n ],\n plugins: [\n SwaggerUIBundle.plugins.DownloadUrl\n ],\n layout: \"StandaloneLayout\",\n validatorUrl: null,\n oauth2RedirectUrl: window.location.origin + '/swagger-ui/oauth2-redirect.html'\n });\n };\n </script>\n</body>\n</html>`;\n}\n\nfunction generateRedocUI(specUrl: string, globalOptions: SwaggerGlobalOptions) {\n return `\n<!DOCTYPE html>\n<html>\n <head>\n <title>${globalOptions.title}</title>\n <meta charset=\"utf-8\"/>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <meta name=\"description\" content=\"${globalOptions.description}\" />\n <link rel=\"icon\" type=\"image/png\" href=\"https://redocly.github.io/redoc/favicon.ico\">\n <style>\n body { margin: 0; padding: 0; }\n </style>\n </head>\n <body>\n <redoc spec-url=\"${specUrl}\"></redoc>\n <script src=\"https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js\"></script>\n </body>\n</html>\n `;\n}\n\nfunction generateRapiDocUI(\n specUrl: string,\n globalOptions: SwaggerGlobalOptions,\n) {\n return `\n<!DOCTYPE html>\n<html>\n <head>\n <title>${globalOptions.title}</title>\n <meta charset=\"utf-8\"/>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <meta name=\"description\" content=\"${globalOptions.description}\" />\n <link rel=\"icon\" type=\"image/png\" href=\"https://mrin9.github.io/RapiDoc/images/favicon.png\">\n <style>\n body { margin: 0; padding: 0; }\n </style>\n </head>\n <body>\n <rapi-doc\n spec-url=\"${specUrl}\"\n render-style=\"read\"\n layout=\"column\"\n show-header=\"true\"\n allow-server-selection=\"true\"\n allow-authentication=\"true\"\n allow-server-variables=\"true\"\n theme=\"light\"\n primary-color=\"#009688\"\n regular-font=\"Open Sans, sans-serif\"\n mono-font=\"Fira Mono, monospace\"\n >\n </rapi-doc>\n <script type=\"module\" src=\"https://unpkg.com/rapidoc/dist/rapidoc-min.js\"></script>\n </body>\n</html>\n `;\n}\n\n/**\n * Convert a TypeBox TSchema to an OpenAPI 3.0 compatible schema (AJV compliant)\n * This is a shallow conversion, as TypeBox is already mostly JSON Schema compatible\n */\nfunction typeboxToOpenAPI(\n schema: TSchema,\n): Omit<TSchema, \"$id\" | \"$schema\"> | undefined {\n if (!schema) {\n return undefined;\n }\n\n const { $id, $schema, ...rest } = schema;\n return rest;\n}\n\n/**\n * Extract path parameters from a route path (e.g., /users/:id -> [{ name: \"id\", in: \"path\", required: true }])\n */\nfunction extractPathParams(path: string, paramSchema?: TSchema): any[] {\n const params: any[] = [];\n const regex = /:([a-zA-Z0-9_]+)/g;\n let match;\n while ((match = regex.exec(path)) !== null) {\n const name = match[1];\n let schema: Record<string, unknown> = { type: \"string\" };\n if (\n paramSchema &&\n paramSchema.type === \"object\" &&\n paramSchema.properties &&\n paramSchema.properties[name]\n ) {\n schema = typeboxToOpenAPI(paramSchema.properties[name]) || {\n type: \"string\",\n };\n }\n params.push({\n name,\n in: \"path\",\n required: true,\n schema,\n });\n }\n return params;\n}\n","import { RouteNotFoundError } from \"src/errors/route_not_found\";\nimport { Request } from \"../../server/http/request\";\nimport { router } from \"../../server/router/router\";\nimport type { ServerInterface } from \"./server_interface\";\nimport type {\n BunTapOptions,\n HttpMethod,\n ServerConnectInput,\n ServerRoute,\n ServerTapOptions,\n} from \"./server_types\";\nimport { executeMiddlewareChain } from \"./server_utils\";\nimport { errorFactory } from \"src/errors/error_factory\";\n\nexport class ServerBun implements ServerInterface {\n port: number;\n hostname: string;\n host: string;\n routes: ServerRoute[];\n tapOptions?: ServerTapOptions;\n declare url: string;\n declare runtimeServer: ReturnType<typeof Bun.serve>;\n\n constructor(input?: ServerConnectInput) {\n this.routes = input?.routes ?? [];\n this.port = input?.port ?? 80;\n this.hostname = input?.host ?? \"0.0.0.0\";\n this.host = input?.host ?? \"0.0.0.0\";\n this.tapOptions = input?.tapOptions;\n }\n\n listen(): void {\n const tapOptions = this.tapOptions?.options as\n | BunTapOptions[\"options\"]\n | undefined;\n const { fetch, ...rest } = tapOptions ?? {};\n\n this.runtimeServer = Bun.serve({\n port: this.port,\n hostname: this.hostname,\n fetch: async (req, server) => {\n const url = new URL(req.url);\n const match = router.find(req.method as HttpMethod, url.pathname);\n\n Request.enrichRequest(req as Request);\n req.params = match?.params ?? {};\n req.query = Object.fromEntries(url.searchParams.entries());\n (req as any).ip =\n req.headers.get(\"x-forwarded-for\")?.split(\",\")[0] ??\n server.requestIP(req)?.address;\n\n // User input handler\n await fetch?.call(this, req, server);\n\n const response = await executeMiddlewareChain(\n match?.middleware ?? [],\n match?.handler ??\n ((req, res) => {\n res.notFound({\n ...errorFactory(new RouteNotFoundError(req.url, req.method)),\n });\n }),\n req as Request,\n );\n\n const responseHeaders = response.headers;\n if (responseHeaders[\"Content-Type\"] === \"application/json\") {\n return Response.json(response.getBody(), {\n status: response.responseStatus,\n headers: response.headers,\n });\n }\n\n return new Response(response.getBody(), {\n status: response.responseStatus,\n headers: response.headers,\n });\n },\n ...(rest as any),\n });\n this.url = this.runtimeServer.url.toString();\n }\n\n async close(): Promise<void> {\n if (!this.runtimeServer) {\n throw new Error(\"Server is not listening or not initialized\");\n }\n\n await this.runtimeServer.stop();\n }\n}\n","import { RouteNotFoundError } from \"src/errors/route_not_found\";\nimport { Request } from \"../../server/http/request\";\nimport { router } from \"../../server/router/router\";\nimport type { ServerInterface } from \"./server_interface\";\nimport type {\n DenoTapOptions,\n HttpMethod,\n ServerConnectInput,\n ServerRoute,\n ServerTapOptions,\n} from \"./server_types\";\nimport { executeMiddlewareChain } from \"./server_utils\";\nimport { errorFactory } from \"src/errors/error_factory\";\n\nexport class ServerDeno implements ServerInterface {\n declare port: number;\n declare hostname: string;\n declare host: string;\n declare url: string;\n declare routes: ServerRoute[];\n declare runtimeServer: ReturnType<typeof Deno.serve>;\n declare tapOptions?: ServerTapOptions;\n\n constructor(input?: ServerConnectInput) {\n this.routes = input?.routes ?? [];\n this.port = input?.port ?? 80;\n this.hostname = input?.host ?? \"0.0.0.0\";\n this.host = input?.host ?? \"0.0.0.0\";\n this.tapOptions = input?.tapOptions;\n }\n\n listen(): void {\n const tapOptions = this.tapOptions?.options as DenoTapOptions[\"options\"];\n const { handler, ...rest } = tapOptions ?? {};\n\n this.runtimeServer = Deno.serve({\n port: this.port,\n hostname: this.hostname,\n handler: async (req, info) => {\n const url = new URL(req.url);\n const match = router.find(req.method as HttpMethod, url.pathname);\n\n Request.enrichRequest(req as Request);\n req.params = match?.params ?? {};\n req.query = Object.fromEntries(url.searchParams.entries());\n (req as any).ip =\n req.headers.get(\"x-forwarded-for\")?.split(\",\")[0] ??\n info.remoteAddr?.hostname;\n\n // User input handler\n await handler?.(req, info);\n\n const res = await executeMiddlewareChain(\n match?.middleware ?? [],\n match?.handler ??\n ((req, res) => {\n res.notFound({\n ...errorFactory(new RouteNotFoundError(req.url, req.method)),\n });\n }),\n req as Request,\n );\n\n const responseHeaders = res.headers;\n if (responseHeaders[\"Content-Type\"] === \"application/json\") {\n return Response.json(res.getBody(), {\n status: res.responseStatus,\n headers: res.headers,\n });\n }\n\n return new Response(res.getBody(), {\n status: res.responseStatus,\n headers: res.headers,\n });\n },\n ...rest,\n });\n\n this.url = `http://${this.host}:${this.port}`;\n }\n\n async close(): Promise<void> {\n if (!this.runtimeServer) {\n throw new Error(\"Server is not listening or not initialized\");\n }\n\n await this.runtimeServer.shutdown();\n }\n}\n","import {\n createServer,\n Server as HttpServer,\n IncomingMessage,\n ServerResponse,\n} from \"node:http\";\nimport { Request } from \"../../server/http/request\";\nimport { router } from \"../../server/router/router\";\nimport type { ServerInterface } from \"./server_interface\";\nimport type {\n HttpMethod,\n NodeTapOptions,\n ServerConnectInput,\n ServerRoute,\n ServerTapOptions,\n} from \"./server_types\";\nimport { canHaveBody, executeMiddlewareChain } from \"./server_utils\";\nimport { RouteNotFoundError } from \"src/errors/route_not_found\";\nimport { errorFactory } from \"src/errors/error_factory\";\n\nasync function pipeReadableStreamToNodeResponse(\n stream: ReadableStream,\n res: ServerResponse,\n) {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) {\n res.end();\n break;\n }\n res.write(value);\n }\n } catch (error) {\n res.destroy(error as Error);\n }\n}\n\nexport class ServerNode implements ServerInterface {\n port: number;\n host: string;\n url: string;\n routes: ServerRoute[];\n tapOptions?: ServerTapOptions;\n runtimeServer: HttpServer;\n\n constructor(input?: ServerConnectInput) {\n this.routes = input?.routes ?? [];\n this.port = input?.port ?? 80;\n this.host = input?.host ?? \"0.0.0.0\";\n this.url = `http://${this.host}:${this.port}`;\n this.tapOptions = input?.tapOptions;\n\n this.runtimeServer = createServer(\n async (\n req: IncomingMessage,\n httpResponse: ServerResponse,\n ): Promise<void> => {\n if (this.tapOptions) {\n const { options } = this.tapOptions as NodeTapOptions;\n await options?.(req);\n }\n\n const match = router.find(req.method as HttpMethod, req.url!);\n const request = new Request(`${this.url}${req.url}`, {\n method: req.method,\n body: canHaveBody(req.method)\n ? await this.readRequestBody(req)\n : undefined,\n headers: req.headers as Record<string, string>,\n });\n\n let forwardedFor = req.headers[\"x-forwarded-for\"];\n if (Array.isArray(forwardedFor)) {\n forwardedFor = forwardedFor[0];\n }\n\n request.ip = forwardedFor ?? req.socket.remoteAddress;\n\n const [_, search = \"\"] = req.url?.split(\"?\", 2) ?? [];\n request.query = Object.fromEntries(new URLSearchParams(search));\n request.params = match?.params ?? {};\n\n const response = await executeMiddlewareChain(\n match?.middleware ?? [],\n match?.handler ??\n ((req, res) => {\n res.notFound({\n ...errorFactory(new RouteNotFoundError(req.url, req.method)),\n });\n }),\n request,\n );\n\n let body = response.getBody();\n if (body instanceof ReadableStream) {\n pipeReadableStreamToNodeResponse(body, httpResponse);\n return;\n }\n\n if (response.headers[\"Content-Type\"] === \"application/json\") {\n body = JSON.stringify(body);\n } else if (typeof body === \"string\") {\n body = body;\n } else if (body instanceof Buffer || body instanceof Uint8Array) {\n body = body;\n } else {\n body = String(body);\n }\n\n httpResponse.writeHead(response.responseStatus, response.headers);\n httpResponse.end(body);\n },\n );\n }\n\n listen(): void {\n this.runtimeServer.listen(this.port, this.host);\n }\n\n async close(): Promise<void> {\n return new Promise((resolve, reject) => {\n this.runtimeServer.close((err) => {\n if (err && \"code\" in err && err.code !== \"ERR_SERVER_NOT_RUNNING\") {\n reject(err);\n } else {\n resolve();\n }\n });\n });\n }\n\n private async readRequestBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk) => chunks.push(Buffer.from(chunk)));\n req.on(\"error\", reject);\n req.on(\"end\", () => resolve(Buffer.concat(chunks).toString()));\n });\n }\n}\n","import { type RunTimeType } from \"../runtime\";\nimport { ServerBun } from \"./server_bun\";\nimport { ServerDeno } from \"./server_deno\";\nimport type { ServerInterface } from \"./server_interface\";\nimport { ServerNode } from \"./server_node\";\nimport type {\n RuntimeServerMap,\n ServerConnectInput,\n ServerRoute,\n} from \"./server_types\";\n\nexport class ServerConnector {\n declare routes: ServerRoute[];\n\n private server: ServerInterface;\n\n constructor(serverOptions?: ServerConnectInput) {\n this.server = this.getRuntimeServer(serverOptions);\n this.routes = this.server.routes;\n }\n\n get url(): string {\n return this.server.url;\n }\n\n get port(): number {\n return this.server.port;\n }\n\n get host(): string {\n return this.server.host;\n }\n\n /**\n * Get the server for the given runtime\n * @example \"node\" returns HttpServer\n * @example \"bun\" returns ReturnType<typeof Bun.serve>\n * @example \"deno\" returns ReturnType<typeof Deno.serve>\n * @param _ - The runtime to get the server for\n * @returns The server for the given runtime\n */\n getServer<T extends RunTimeType>(_: T): RuntimeServerMap<T> {\n return this.server.runtimeServer as RuntimeServerMap<T>;\n }\n\n listen(): void {\n return this.server.listen();\n }\n\n close(): Promise<void> {\n return this.server.close();\n }\n\n private getRuntimeServer(\n serverOptions?: ServerConnectInput,\n ): ServerInterface {\n if (serverOptions?.runtime === \"bun\") {\n return new ServerBun(serverOptions);\n } else if (serverOptions?.runtime === \"node\") {\n return new ServerNode(serverOptions);\n } else if (serverOptions?.runtime === \"deno\") {\n return new ServerDeno(serverOptions);\n }\n\n // TODO: BaldaError implementation\n throw new Error(\n \"No server implementation found for runtime: \" + serverOptions?.runtime,\n );\n }\n}\n","export const PROTECTED_KEYS = [\n \"isListening\",\n \"url\",\n \"port\",\n \"host\",\n \"routes\",\n \"embed\",\n \"constructor\",\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"getNodeServer\",\n \"getBunServer\",\n \"getDenoServer\",\n \"use\",\n \"setErrorHandler\",\n \"listen\",\n \"close\",\n \"tapOptions\",\n \"startUpOptions\",\n \"tmpDir\",\n \"logger\",\n \"getMockServer\",\n];\n","import { Response } from \"../server/http/response\";\n\nexport class MockResponse<T = any> {\n constructor(private readonly response: Response) {}\n\n // base getters\n body(): T {\n return this.response.getBody();\n }\n\n statusCode(): number {\n return this.response.responseStatus;\n }\n\n headers(): Record<string, string> {\n return this.response.headers;\n }\n\n // assertions\n assertStatus(status: number): this {\n if (this.response.responseStatus !== status) {\n throw new Error(\n `Expected status ${status}, but got ${this.response.responseStatus}`,\n );\n }\n return this;\n }\n\n assertHeader(header: string, value: string): this {\n if (this.response.headers[header] !== value) {\n throw new Error(\n `Expected header ${header} to be ${value}, but got ${this.response.headers[header]}`,\n );\n }\n return this;\n }\n\n assertHeaderExists(header: string): this {\n if (!(header in this.response.headers)) {\n throw new Error(\n `Expected header ${header} to exist, but it was not found`,\n );\n }\n return this;\n }\n\n assertHeaderNotExists(header: string): this {\n if (header in this.response.headers) {\n throw new Error(\n `Expected header ${header} to not exist, but it was found with value: ${this.response.headers[header]}`,\n );\n }\n return this;\n }\n\n // TODO: body assertions\n\n assertBodySubset(subset: Partial<T>): this {\n this.assertSubset(this.body(), subset, \"body\");\n return this;\n }\n\n assertBodyDeepEqual(expected: T): this {\n this.assertDeepEqual(this.body(), expected, \"body\");\n return this;\n }\n\n assertBodyNotSubset(subset: Partial<T>): this {\n this.assertNotSubset(this.body(), subset, \"body\");\n return this;\n }\n\n assertBodyNotDeepEqual(expected: T): this {\n this.assertNotDeepEqual(this.body(), expected, \"body\");\n return this;\n }\n\n assertCustom(assertion: (response: Response) => void): this {\n assertion(this.response);\n return this;\n }\n\n private assertSubset(target: any, subset: any, path: string): void {\n for (const key in subset) {\n const currentPath = path === \"\" ? key : `${path}.${key}`;\n const targetValue = target[key];\n const subsetValue = subset[key];\n\n if (!(key in target)) {\n throw new Error(\n `Expected ${path} to have key ${key}, but it was not found`,\n );\n }\n\n if (this.isObject(subsetValue) && this.isObject(targetValue)) {\n this.assertSubset(targetValue, subsetValue, currentPath);\n } else if (Array.isArray(subsetValue) && Array.isArray(targetValue)) {\n this.assertArraySubset(targetValue, subsetValue, currentPath);\n } else if (targetValue !== subsetValue) {\n throw new Error(\n `Expected ${currentPath} to be ${subsetValue}, but got ${targetValue}`,\n );\n }\n }\n }\n\n private assertDeepEqual(target: any, expected: any, path: string): void {\n if (this.isObject(target) && this.isObject(expected)) {\n const targetKeys = Object.keys(target);\n const expectedKeys = Object.keys(expected);\n\n if (targetKeys.length !== expectedKeys.length) {\n throw new Error(\n `Expected ${path} to have ${expectedKeys.length} keys, but got ${targetKeys.length}`,\n );\n }\n\n for (const key of expectedKeys) {\n const currentPath = path === \"body\" ? key : `${path}.${key}`;\n this.assertDeepEqual(target[key], expected[key], currentPath);\n }\n } else if (Array.isArray(target) && Array.isArray(expected)) {\n this.assertArrayDeepEqual(target, expected, path);\n } else if (target !== expected) {\n throw new Error(`Expected ${path} to be ${expected}, but got ${target}`);\n }\n }\n\n private assertNotSubset(target: any, subset: any, path: string): void {\n try {\n this.assertSubset(target, subset, path);\n throw new Error(\n `Expected ${path} to NOT contain the subset, but it does`,\n );\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"Expected\")) {\n // Original assertion failed, which means it's NOT a subset - this is what we want\n return;\n }\n throw error;\n }\n }\n\n private assertNotDeepEqual(target: any, expected: any, path: string): void {\n try {\n this.assertDeepEqual(target, expected, path);\n throw new Error(`Expected ${path} to NOT be deeply equal, but it is`);\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"Expected\")) {\n // Original assertion failed, which means they're NOT equal - this is what we want\n return;\n }\n throw error;\n }\n }\n\n private assertArraySubset(target: any[], subset: any[], path: string): void {\n if (subset.length > target.length) {\n throw new Error(\n `Expected ${path} to have at least ${subset.length} elements, but got ${target.length}`,\n );\n }\n\n for (let i = 0; i < subset.length; i++) {\n const currentPath = `${path}[${i}]`;\n const targetValue = target[i];\n const subsetValue = subset[i];\n\n if (this.isObject(subsetValue) && this.isObject(targetValue)) {\n this.assertSubset(targetValue, subsetValue, currentPath);\n } else if (Array.isArray(subsetValue) && Array.isArray(targetValue)) {\n this.assertArraySubset(targetValue, subsetValue, currentPath);\n } else if (targetValue !== subsetValue) {\n throw new Error(\n `Expected ${currentPath} to be ${subsetValue}, but got ${targetValue}`,\n );\n }\n }\n }\n\n private assertArrayDeepEqual(\n target: any[],\n expected: any[],\n path: string,\n ): void {\n if (target.length !== expected.length) {\n throw new Error(\n `Expected ${path} to have ${expected.length} elements, but got ${target.length}`,\n );\n }\n\n for (let i = 0; i < expected.length; i++) {\n const currentPath = `${path}[${i}]`;\n this.assertDeepEqual(target[i], expected[i], currentPath);\n }\n }\n\n private isObject(value: any): boolean {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n }\n}\n","import { logger } from \"src/logger/logger\";\nimport { MockResponse } from \"src/mock/mock_response\";\nimport { MockServerOptions } from \"src/mock/mock_server_types\";\nimport { HttpMethod } from \"src/runtime/native_server/server_types\";\nimport {\n canHaveBody,\n executeMiddlewareChain,\n} from \"src/runtime/native_server/server_utils\";\nimport { Request } from \"src/server/http/request\";\nimport { Response } from \"src/server/http/response\";\nimport { router } from \"src/server/router/router\";\nimport type { Server } from \"src/server/server\";\n\n/**\n * Allows to mock server requests without needing to start the server, useful for testing purposes\n */\nexport class MockServer {\n private readonly server: Server;\n\n constructor(server: Server) {\n this.server = server;\n }\n\n /**\n * Simulates an HTTP request without making an actual network call, useful for testing purposes\n * Executes the middleware chain and handler of the route\n * @param method - The HTTP method (GET, POST, PUT, DELETE, PATCH)\n * @param path - The request path\n * @param options - Request options including body, headers, query params, etc.\n * @throws {Error} - If more than one of body, formData, urlencoded is provided\n */\n async request<T>(\n method: HttpMethod,\n path: string,\n options: MockServerOptions = {},\n ): Promise<MockResponse<T>> {\n const { headers = {}, query = {}, cookies = {}, ip } = options;\n this.validateOptions(options);\n\n const route = router.find(method.toUpperCase(), path);\n if (!route) {\n const res = new Response(404);\n res.json({\n caller: \"MockServer\",\n error: \"Route not found\",\n path,\n method,\n });\n return new MockResponse(res);\n }\n\n let body = options.body;\n let contentType = \"application/json\";\n\n if (\n body &&\n typeof body === \"object\" &&\n !(body instanceof Uint8Array) &&\n !(body instanceof ArrayBuffer)\n ) {\n body = JSON.stringify(body);\n }\n\n if (options.formData) {\n const boundary = `----WebKitFormBoundary${Math.random().toString(36).substring(2)}`;\n contentType = `multipart/form-data; boundary=${boundary}`;\n\n const multipartBody = await this.formDataToMultipart(\n options.formData,\n boundary,\n );\n body = multipartBody;\n }\n\n if (options.urlencoded) {\n contentType = \"application/x-www-form-urlencoded\";\n body = new URLSearchParams(options.urlencoded).toString();\n }\n\n const url = new URL(\n `http://${this.server.host}:${this.server.port}${path}`,\n );\n url.search = new URLSearchParams(query).toString();\n\n const req = new Request(url.toString(), {\n method: method.toUpperCase(),\n body: canHaveBody(method) ? body : undefined,\n headers: {\n \"content-type\": contentType,\n ...headers,\n },\n });\n\n req.query = { ...Object.fromEntries(url.searchParams.entries()), ...query };\n req.params = route.params;\n req.cookies = cookies;\n req.ip = ip;\n\n try {\n const res = await executeMiddlewareChain(\n route.middleware,\n route.handler,\n req,\n );\n return new MockResponse(res);\n } catch (error) {\n logger.error(`Error processing mock request ${method} ${path}:`, error);\n const errorRes = new Response(500);\n errorRes.json({\n error: \"Internal server error\",\n message: error instanceof Error ? error.message : String(error),\n });\n return new MockResponse(errorRes);\n }\n }\n\n async get<T>(\n path: string,\n options?: Omit<MockServerOptions, \"body\" | \"formData\" | \"urlencoded\">,\n ): Promise<MockResponse<T>> {\n return this.request(\"GET\", path, options);\n }\n\n async post<T>(\n path: string,\n options?: MockServerOptions,\n ): Promise<MockResponse<T>> {\n return this.request(\"POST\", path, options);\n }\n\n async put<T>(\n path: string,\n options?: MockServerOptions,\n ): Promise<MockResponse<T>> {\n return this.request(\"PUT\", path, options);\n }\n\n async patch<T>(\n path: string,\n options?: MockServerOptions,\n ): Promise<MockResponse<T>> {\n return this.request(\"PATCH\", path, options);\n }\n\n async delete<T>(\n path: string,\n options?: Omit<MockServerOptions, \"body\" | \"formData\">,\n ): Promise<MockResponse<T>> {\n return this.request(\"DELETE\", path, options);\n }\n\n /**\n * Converts FormData to a proper multipart/form-data body with boundaries\n */\n private async formDataToMultipart(\n formData: FormData,\n boundary: string,\n ): Promise<Uint8Array> {\n const encoder = new TextEncoder();\n const buffers: Uint8Array[] = [];\n\n for (const [name, value] of formData.entries()) {\n buffers.push(encoder.encode(`--${boundary}\\r\\n`));\n\n let disposition = `Content-Disposition: form-data; name=\"${name}\"`;\n let contentType = \"\";\n\n if ((value as any) instanceof File) {\n disposition += `; filename=\"${(value as any).name}\"`;\n contentType = `Content-Type: ${(value as any).type || \"application/octet-stream\"}\\r\\n`;\n }\n\n buffers.push(encoder.encode(`${disposition}\\r\\n${contentType}\\r\\n`));\n\n if ((value as any) instanceof File) {\n const arrayBuffer = await (value as any).arrayBuffer();\n buffers.push(new Uint8Array(arrayBuffer));\n buffers.push(encoder.encode(\"\\r\\n\"));\n } else {\n buffers.push(encoder.encode(`${String(value)}\\r\\n`));\n }\n }\n\n buffers.push(encoder.encode(`--${boundary}--\\r\\n`));\n\n const totalLength = buffers.reduce((sum, b) => sum + b.byteLength, 0);\n const multipartBody = new Uint8Array(totalLength);\n let offset = 0;\n for (const buf of buffers) {\n multipartBody.set(buf, offset);\n offset += buf.byteLength;\n }\n\n return multipartBody;\n }\n\n private validateOptions(options: MockServerOptions) {\n const { body, formData, urlencoded } = options;\n if (body && (formData || urlencoded)) {\n throw new Error(\"Only one of body, formData, urlencoded can be provided\");\n }\n\n if (formData && (urlencoded || body)) {\n throw new Error(\"Only one of formData, urlencoded can be provided\");\n }\n\n if (urlencoded && (body || formData)) {\n throw new Error(\"Only one of urlencoded, body can be provided\");\n }\n }\n}\n","import type { UrlEncodedOptions } from \"src/plugins/urlencoded/urlencoded_types\";\nimport type { ServerRouteMiddleware } from \"../../runtime/native_server/server_types\";\nimport type { NextFunction } from \"../../server/http/next\";\nimport type { Request } from \"../../server/http/request\";\nimport type { Response } from \"../../server/http/response\";\n\n/**\n * URL-encoded form data parser middleware\n * Parses application/x-www-form-urlencoded bodies and populates req.body\n * @param options URL-encoded parsing options\n * @param options.limit The maximum size of the URL-encoded body in bytes. Defaults to 1MB.\n * @param options.extended Whether to parse extended syntax (objects and arrays). Defaults to false.\n * @param options.charset The character encoding to use when parsing. Defaults to 'utf8'.\n * @param options.allowEmpty Whether to allow empty values. Defaults to true.\n * @param options.parameterLimit Maximum number of parameters to parse. Defaults to 1000.\n */\nexport const urlencoded = (\n options?: UrlEncodedOptions,\n): ServerRouteMiddleware => {\n const opts: Required<UrlEncodedOptions> = {\n limit: 1024 * 1024,\n extended: false,\n charset: \"utf8\",\n allowEmpty: true,\n parameterLimit: 1000,\n ...options,\n };\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const contentType = req.headers.get(\"content-type\") || \"\";\n if (!contentType.includes(\"application/x-www-form-urlencoded\")) {\n return next();\n }\n\n try {\n await parseUrlEncodedBody(req, opts);\n await next();\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"limit\")) {\n res.status(413).json({\n error: \"Payload too large\",\n message: \"Request body exceeds the size limit\",\n });\n return;\n }\n\n throw error;\n }\n };\n};\n\n/**\n * Parse URL-encoded body and populate req.body\n */\nasync function parseUrlEncodedBody(\n req: Request,\n opts: Required<UrlEncodedOptions>,\n): Promise<void> {\n const arrayBuffer = req.rawBody!;\n\n if (arrayBuffer.byteLength > opts.limit) {\n throw new Error(\n `Body size ${arrayBuffer.byteLength} exceeds limit ${opts.limit}`,\n );\n }\n\n const decoder = new TextDecoder(opts.charset);\n const bodyString = decoder.decode(arrayBuffer);\n const parsed = parseUrlEncodedString(bodyString, opts);\n req.body = parsed;\n}\n\n/**\n * Parse URL-encoded string into an object\n */\nfunction parseUrlEncodedString(\n str: string,\n opts: Required<UrlEncodedOptions>,\n): Record<string, any> {\n const result: Record<string, any> = {};\n const searchParams = new URLSearchParams(str);\n if (searchParams.size > opts.parameterLimit) {\n throw new Error(\n `Too many parameters: ${searchParams.size} exceeds limit ${opts.parameterLimit}`,\n );\n }\n\n for (const [key, value] of searchParams.entries()) {\n if (!opts.allowEmpty && value === \"\") {\n continue;\n }\n\n if (opts.extended) {\n setNestedValue(result, key, value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Set nested value for extended mode (e.g., user[name]=john -> { user: { name: 'john' } })\n */\nfunction setNestedValue(\n obj: Record<string, any>,\n key: string,\n value: string,\n): void {\n const keys = key.match(/\\[([^\\]]*)\\]/g);\n if (!keys) {\n obj[key] = value;\n return;\n }\n\n let current = obj;\n const baseKey = key.split(\"[\")[0];\n\n for (let i = 0; i < keys.length - 1; i++) {\n const bracketKey = keys[i].slice(1, -1);\n if (!current[baseKey]) {\n current[baseKey] = {};\n }\n\n if (bracketKey === \"\") {\n if (!Array.isArray(current[baseKey])) {\n current[baseKey] = [];\n }\n current = current[baseKey];\n continue;\n }\n\n if (!current[baseKey][bracketKey]) {\n current[baseKey][bracketKey] = {};\n }\n\n current = current[baseKey][bracketKey];\n }\n\n const lastKey = keys[keys.length - 1].slice(1, -1);\n if (lastKey === \"\") {\n if (!Array.isArray(current)) {\n current = [];\n }\n\n current.push(value);\n return;\n }\n\n current[lastKey] = value;\n}\n","import { glob } from \"glob\";\nimport { type TaskContext } from \"node-cron\";\nimport { CronSchedule, CronScheduleParams } from \"src/cron/cron.types\";\nimport { BaldaError } from \"src/errors/balda_error\";\nimport { logger } from \"src/logger/logger\";\n\nexport class CronService {\n static scheduledJobs: CronSchedule[] = [];\n\n /**\n * @description Schedule a cron job.\n * @internal\n * @example\n * CronService.register('test', '0 0 * * *', () => {\n * console.log('test');\n * }, {\n * timezone: 'Europe/Istanbul',\n * });\n */\n static register(name: string, ...args: CronScheduleParams): void {\n args[2] = {\n name,\n ...args[2],\n };\n\n this.scheduledJobs.push({ name, args });\n }\n\n /**\n * @description Start the cron scheduler.\n */\n static async run() {\n const nodeCronModule = (\n await import(\"node-cron\").catch(() => {\n throw new BaldaError(\n \"node-cron not installed as a dependency, it is required in order to run cron jobs with the @cron decorator\",\n );\n })\n ).default;\n\n logger.info(\"Scheduling cron jobs\");\n if (!this.scheduledJobs.length) {\n logger.info(\"No cron jobs to schedule\");\n return;\n }\n\n for (const { name, args } of this.scheduledJobs) {\n logger.info(`Scheduling cron job: ${name}`);\n const scheduledJob = nodeCronModule.schedule(...args);\n scheduledJob.on(\"execution:failed\", (context) =>\n this.globalErrorHandler(context),\n );\n }\n\n logger.info(\"Cron jobs scheduled\");\n }\n\n /**\n * @description Main error handler for cron jobs. You can write your own error handler by overriding this static method for example with sentry.\n */\n static globalErrorHandler(context: TaskContext) {\n logger.error(context.execution?.error);\n }\n\n /**\n * @description Import all cron jobs from the app/cron/schedules directory\n */\n static async massiveImportCronJobs(cronJobPatterns: string[]) {\n const allFiles: string[] = [];\n\n for (const pattern of cronJobPatterns) {\n const files = await glob(pattern);\n allFiles.push(...files);\n }\n\n await Promise.all(\n allFiles.map(async (file) => {\n await import(file).catch((error) => {\n logger.error(`Error importing cron job: ${file}`);\n logger.error(error);\n });\n }),\n );\n }\n}\n\nexport const setCronGlobalErrorHandler = (\n globalErrorHandler: (\n ...args: Parameters<(typeof CronService)[\"globalErrorHandler\"]>\n ) => void,\n) => {\n CronService.globalErrorHandler = globalErrorHandler.bind(CronService);\n};\n","import type { ServerRouteMiddleware } from \"src/runtime/native_server/server_types\";\n\n/**\n * Base class for all plugins.\n *\n * Plugins are used to extend the functionality of the server.\n *\n * @example\n * ```ts\n * import { Server, BasePlugin } from \"balda\";\n *\n * export class MyPlugin extends BasePlugin {\n * async handle(): Promise<ServerRouteMiddleware> {\n * return async (req, res, next) => {\n * console.log(\"My plugin is running\");\n * await next();\n * };\n * }\n * }\n *\n * const server = new Server();\n * server.use(new MyPlugin().handle());\n * ```\n *\n * @abstract\n */\nexport abstract class BasePlugin {\n abstract handle(...args: any[]): Promise<ServerRouteMiddleware>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,iBAAAA;AAAA,EAAA,gBAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,uBAAqB;;;ACGd,IAAM,gBAAN,MAAoB;AAAA,EACzB,OAAe,WAAW,oBAAI,QAAwC;AAAA;AAAA;AAAA;AAAA,EAKtE,OAAO,IAAI,QAAa,aAAqB,OAAkB;AAC7D,QAAI,CAAC,KAAK,SAAS,IAAI,MAAM,GAAG;AAC9B,WAAK,SAAS,IAAI,QAAQ,oBAAI,IAAI,CAAC;AAAA,IACrC;AACA,SAAK,SAAS,IAAI,MAAM,EAAG,IAAI,aAAa,KAAK;AAAA,EACnD;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,IAAI,QAAa,aAA0B;AAChD,WAAO,KAAK,SAAS,IAAI,MAAM,GAAG,IAAI,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F;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,CAAC;AAAA,MACD,CAAC,KAAK,QAAQ;AACZ,cAAM,gBAAgB,IAAI,mBAAmB,IAAI,KAAK,IAAI,MAAM;AAChE,YAAI,SAAS;AAAA,UACX,GAAG,aAAa,aAAa;AAAA,QAC/B,CAAC;AAAA,MACH;AAAA,MACA;AAAA,QACE,oBAAoB;AAAA,MACtB;AAAA,IACF;AAEA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,CAAC;AAAA,MACD,CAAC,KAAK,QAAQ;AACZ,cAAM,gBAAgB,IAAI,mBAAmB,IAAI,KAAK,IAAI,MAAM;AAChE,YAAI,SAAS;AAAA,UACX,GAAG,aAAa,aAAa;AAAA,QAC/B,CAAC;AAAA,MACH;AAAA,MACA;AAAA,QACE,oBAAoB;AAAA,MACtB;AAAA,IACF;AAAA,EACF;AACF;;;AwB/gBO,IAAe,aAAf,MAA0B;AAEjC;;;AjDOO,IAAMC,UAAS;","names":["Request","Response","router","middleware","middleware","meta","import_ajv","addFormats","Ajv","validate","Request","fs","import_node_path","fs","Response","import_glob","import_node_path","pino","Response","middleware","import_node_path","json","getContentType","Request","req","Request","req","res","Request","req","resolve","Response","Request","urlencoded","router"]}