arkos 1.4.0-canary.92 → 1.4.1-beta

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 (170) hide show
  1. package/dist/cjs/app.js +1 -1
  2. package/dist/cjs/app.js.map +1 -1
  3. package/dist/cjs/exports/index.js.map +1 -1
  4. package/dist/cjs/modules/auth/auth.controller.js +1 -1
  5. package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
  6. package/dist/cjs/modules/auth/auth.service.js +3 -4
  7. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  8. package/dist/cjs/modules/auth/utils/services/auth-action.service.js +56 -8
  9. package/dist/cjs/modules/auth/utils/services/auth-action.service.js.map +1 -1
  10. package/dist/cjs/modules/base/base.controller.js +6 -3
  11. package/dist/cjs/modules/base/base.controller.js.map +1 -1
  12. package/dist/cjs/modules/base/base.middlewares.js +17 -5
  13. package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
  14. package/dist/cjs/modules/error-handler/error-handler.controller.js +2 -2
  15. package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
  16. package/dist/cjs/modules/error-handler/utils/catch-async.js.map +1 -1
  17. package/dist/cjs/modules/swagger/swagger.router.js +6 -4
  18. package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
  19. package/dist/cjs/modules/swagger/utils/built-in-route-path-object-manager.js +7 -0
  20. package/dist/cjs/modules/swagger/utils/built-in-route-path-object-manager.js.map +1 -0
  21. package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +326 -183
  22. package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
  23. package/dist/cjs/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js +374 -288
  24. package/dist/cjs/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js.map +1 -1
  25. package/dist/cjs/modules/swagger/utils/helpers/get-swagger-default-configs.js +1 -5
  26. package/dist/cjs/modules/swagger/utils/helpers/get-swagger-default-configs.js.map +1 -1
  27. package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths.js +280 -243
  28. package/dist/cjs/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths.js.map +1 -1
  29. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
  30. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  31. package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js +8 -6
  32. package/dist/cjs/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
  33. package/dist/cjs/server.js +17 -15
  34. package/dist/cjs/server.js.map +1 -1
  35. package/dist/cjs/types/index.js.map +1 -1
  36. package/dist/cjs/types/new-arkos-config.js.map +1 -1
  37. package/dist/cjs/utils/arkos-router/index.js +50 -10
  38. package/dist/cjs/utils/arkos-router/index.js.map +1 -1
  39. package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
  40. package/dist/cjs/utils/arkos-router/utils/helpers/index.js +11 -0
  41. package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
  42. package/dist/cjs/utils/cli/dev.js +13 -55
  43. package/dist/cjs/utils/cli/dev.js.map +1 -1
  44. package/dist/cjs/utils/cli/export-auth-action.js +1 -1
  45. package/dist/cjs/utils/cli/export-auth-action.js.map +1 -1
  46. package/dist/cjs/utils/cli/generate.js +3 -3
  47. package/dist/cjs/utils/cli/generate.js.map +1 -1
  48. package/dist/cjs/utils/cli/index.js +1 -1
  49. package/dist/cjs/utils/cli/index.js.map +1 -1
  50. package/dist/cjs/utils/cli/start.js +19 -12
  51. package/dist/cjs/utils/cli/start.js.map +1 -1
  52. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  53. package/dist/cjs/utils/cli/utils/runtime-cli-commander.js +51 -6
  54. package/dist/cjs/utils/cli/utils/runtime-cli-commander.js.map +1 -1
  55. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +3 -3
  56. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +1 -1
  57. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +3 -3
  58. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +1 -1
  59. package/dist/cjs/utils/cli/utils/template-generator/templates/middlewares-template.js +6 -3
  60. package/dist/cjs/utils/cli/utils/template-generator/templates/middlewares-template.js.map +1 -1
  61. package/dist/cjs/utils/cli/utils/template-generator/templates/router-template.js +3 -1
  62. package/dist/cjs/utils/cli/utils/template-generator/templates/router-template.js.map +1 -1
  63. package/dist/cjs/utils/dotenv.helpers.js +15 -7
  64. package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
  65. package/dist/cjs/utils/helpers/api.features.helpers.js +174 -81
  66. package/dist/cjs/utils/helpers/api.features.helpers.js.map +1 -1
  67. package/dist/cjs/utils/helpers/prisma.helpers.js +40 -1
  68. package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
  69. package/dist/cjs/utils/helpers/routers.helpers.js +0 -1
  70. package/dist/cjs/utils/helpers/routers.helpers.js.map +1 -1
  71. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +19 -4
  72. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  73. package/dist/cjs/utils/validate-dto.js +1 -5
  74. package/dist/cjs/utils/validate-dto.js.map +1 -1
  75. package/dist/cjs/utils/validate-schema.js +2 -7
  76. package/dist/cjs/utils/validate-schema.js.map +1 -1
  77. package/dist/esm/app.js +1 -1
  78. package/dist/esm/app.js.map +1 -1
  79. package/dist/esm/exports/index.js.map +1 -1
  80. package/dist/esm/modules/auth/auth.controller.js +1 -1
  81. package/dist/esm/modules/auth/auth.controller.js.map +1 -1
  82. package/dist/esm/modules/auth/auth.service.js +4 -5
  83. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  84. package/dist/esm/modules/auth/utils/services/auth-action.service.js +56 -5
  85. package/dist/esm/modules/auth/utils/services/auth-action.service.js.map +1 -1
  86. package/dist/esm/modules/base/base.controller.js +6 -3
  87. package/dist/esm/modules/base/base.controller.js.map +1 -1
  88. package/dist/esm/modules/base/base.middlewares.js +17 -5
  89. package/dist/esm/modules/base/base.middlewares.js.map +1 -1
  90. package/dist/esm/modules/error-handler/error-handler.controller.js +2 -2
  91. package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
  92. package/dist/esm/modules/error-handler/utils/catch-async.js.map +1 -1
  93. package/dist/esm/modules/swagger/swagger.router.js +6 -4
  94. package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
  95. package/dist/esm/modules/swagger/utils/built-in-route-path-object-manager.js +5 -0
  96. package/dist/esm/modules/swagger/utils/built-in-route-path-object-manager.js.map +1 -0
  97. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +326 -183
  98. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
  99. package/dist/esm/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js +374 -288
  100. package/dist/esm/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js.map +1 -1
  101. package/dist/esm/modules/swagger/utils/helpers/get-swagger-default-configs.js +1 -2
  102. package/dist/esm/modules/swagger/utils/helpers/get-swagger-default-configs.js.map +1 -1
  103. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths.js +280 -243
  104. package/dist/esm/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths.js.map +1 -1
  105. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
  106. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  107. package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js +8 -6
  108. package/dist/esm/modules/swagger/utils/helpers/swagger.router.helpers.js.map +1 -1
  109. package/dist/esm/server.js +17 -15
  110. package/dist/esm/server.js.map +1 -1
  111. package/dist/esm/types/index.js.map +1 -1
  112. package/dist/esm/types/new-arkos-config.js.map +1 -1
  113. package/dist/esm/utils/arkos-router/index.js +51 -11
  114. package/dist/esm/utils/arkos-router/index.js.map +1 -1
  115. package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
  116. package/dist/esm/utils/arkos-router/utils/helpers/index.js +10 -0
  117. package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
  118. package/dist/esm/utils/cli/dev.js +14 -56
  119. package/dist/esm/utils/cli/dev.js.map +1 -1
  120. package/dist/esm/utils/cli/export-auth-action.js +1 -1
  121. package/dist/esm/utils/cli/export-auth-action.js.map +1 -1
  122. package/dist/esm/utils/cli/generate.js +3 -3
  123. package/dist/esm/utils/cli/generate.js.map +1 -1
  124. package/dist/esm/utils/cli/index.js +1 -1
  125. package/dist/esm/utils/cli/index.js.map +1 -1
  126. package/dist/esm/utils/cli/start.js +19 -12
  127. package/dist/esm/utils/cli/start.js.map +1 -1
  128. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  129. package/dist/esm/utils/cli/utils/runtime-cli-commander.js +52 -7
  130. package/dist/esm/utils/cli/utils/runtime-cli-commander.js.map +1 -1
  131. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +3 -3
  132. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +1 -1
  133. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +3 -3
  134. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +1 -1
  135. package/dist/esm/utils/cli/utils/template-generator/templates/middlewares-template.js +6 -3
  136. package/dist/esm/utils/cli/utils/template-generator/templates/middlewares-template.js.map +1 -1
  137. package/dist/esm/utils/cli/utils/template-generator/templates/router-template.js +3 -1
  138. package/dist/esm/utils/cli/utils/template-generator/templates/router-template.js.map +1 -1
  139. package/dist/esm/utils/dotenv.helpers.js +15 -7
  140. package/dist/esm/utils/dotenv.helpers.js.map +1 -1
  141. package/dist/esm/utils/helpers/api.features.helpers.js +174 -81
  142. package/dist/esm/utils/helpers/api.features.helpers.js.map +1 -1
  143. package/dist/esm/utils/helpers/prisma.helpers.js +39 -1
  144. package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
  145. package/dist/esm/utils/helpers/routers.helpers.js +0 -1
  146. package/dist/esm/utils/helpers/routers.helpers.js.map +1 -1
  147. package/dist/esm/utils/prisma/prisma-json-schema-generator.js +19 -4
  148. package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  149. package/dist/esm/utils/validate-dto.js +1 -2
  150. package/dist/esm/utils/validate-dto.js.map +1 -1
  151. package/dist/esm/utils/validate-schema.js +2 -4
  152. package/dist/esm/utils/validate-schema.js.map +1 -1
  153. package/dist/types/exports/index.d.ts +2 -1
  154. package/dist/types/modules/auth/auth.router.d.ts +1 -1
  155. package/dist/types/modules/auth/auth.service.d.ts +2 -2
  156. package/dist/types/modules/base/base.router.d.ts +1 -1
  157. package/dist/types/modules/swagger/utils/built-in-route-path-object-manager.d.ts +4 -0
  158. package/dist/types/modules/swagger/utils/helpers/get-authentication-json-schema-paths.d.ts +1 -1
  159. package/dist/types/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.d.ts +1 -1
  160. package/dist/types/modules/swagger/utils/helpers/json-schema-generators/prisma-models/generate-prisma-model-main-routes-paths.d.ts +1 -1
  161. package/dist/types/modules/swagger/utils/helpers/swagger.router.helpers.d.ts +1 -1
  162. package/dist/types/types/index.d.ts +5 -5
  163. package/dist/types/types/new-arkos-config.d.ts +1 -1
  164. package/dist/types/utils/arkos-router/index.d.ts +2 -1
  165. package/dist/types/utils/arkos-router/types/index.d.ts +15 -14
  166. package/dist/types/utils/arkos-router/utils/helpers/index.d.ts +1 -0
  167. package/dist/types/utils/cli/dev.d.ts +1 -1
  168. package/dist/types/utils/cli/start.d.ts +1 -1
  169. package/dist/types/utils/helpers/prisma.helpers.d.ts +1 -0
  170. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"new-arkos-config.js","sourceRoot":"","sources":["../../../src/types/new-arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport type { ApiReferenceConfiguration } from \"@scalar/express-api-reference\" with { \"resolution-mode\": \"import\" };\nimport nodemailer from \"nodemailer\";\nimport { ModuleComponents } from \"../utils/dynamic-loader\";\nimport { ArkosRequestHandler } from \".\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for details.\n */\n authentication?: {\n enabled?: boolean;\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: Partial<RateLimitOptions>;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?: {\n /**\n * Defines whether to use strict request validation, it means in every request using `ArkosRouter()` you must pass the validation options with all options (e.g: query, params, body, etc.).\n *\n * **How It Works:**\n * - If it is true, Arkos will require all the options a stated above on the routes and if you don't pass it will throw an error.\n * **What if you don't want to pass a validator to some options?**\n * - You will need to pass `undefined` to the validator option (see example below), this way Arkos will throw an error if something is passed to `req.query` if you passed undefined as validator into `validation.query`\n *\n * ```ts\n * import { ArkosRouter } from \"arkos\"\n *\n * const router = ArkosRouter()\n *\n * router.get({\n * route: \"/api/posts\",\n * validation: {\n * query: undefined\n * }\n * })\n *\n * ```\n */\n strict?: boolean;\n } & (\n | {\n resolver: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver: \"zod\";\n validationOptions?: Record<string, any>;\n }\n );\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStatic?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Defines express middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compression?: false | compression.CompressionOptions | ArkosRequestHandler;\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: false | Partial<RateLimitOptions> | ArkosRequestHandler;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customHandler] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customHandler` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?:\n | false\n | {\n /**\n * Defines allowed origins to acess the API.\n */\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n }\n | ArkosRequestHandler;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n expressJson?:\n | false\n | Parameters<typeof express.json>[0]\n | ArkosRequestHandler;\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParser?:\n | false\n | Parameters<typeof cookieParser>\n | ArkosRequestHandler;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParser?: false | QueryParserOptions | ArkosRequestHandler;\n /**\n * Configuration for request logger middleware.\n *\n * Logs incoming HTTP requests with details such as method, URL, status code, and response time.\n * Useful for debugging and monitoring API traffic.\n */\n requestLogger?: false | ArkosRequestHandler;\n /**\n * Configuration for global error handler middleware.\n *\n * Catches and processes errors thrown in route handlers and other middlewares.\n * Provides a centralized way to format error responses and log errors.\n */\n errorHandler?: false | express.ErrorRequestHandler;\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Strict mode configuration for routing security\n *\n * @default false\n * - all CRUD + Auth (if using auth) endpoits are enabled and avialable by default.\n *\n * When enabled:\n * - If `true`: All CRUD endpoints start disabled and must be explicitly enabled\n * in each model's router configuration\n * - If `'no-bulk'`: Bulk operations (createMany, updateMany, deleteMany) are disabled\n * by default, while individual operations can be enabled per model\n *\n * This provides enhanced security by ensuring no routes are accidentally exposed.\n * Use this in production environments to follow the principle of least privilege.\n *\n * See documentation: https://www.arkosjs.com/docs/guide/security#strict-mode\n */\n strict?: boolean | \"no-bulk\";\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeRoute?: false | ArkosRequestHandler;\n };\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n } & Parameters<typeof nodemailer.createTransport>[0];\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas.\n *\n * **Important**: Is worth mentioning that this works alongside `@scalar/express-api-reference` npm package, you define it's ApiReferenceConfiguration under ``. also consider checking the package documentation at []\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * defintion: {\n * info: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n * Allows `Arkos.js` to fallback to prisma schema and use them as json schema for defining request body and response data\n * when a given zod Schema or class-validator Class is not found to be transformed to json schema.\n *\n * @default false\n */\n strict?: boolean;\n /**\n * Defines your swagger configurations\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n /**\n * Custom `@scalar/express-api-reference` package options.\n *\n * @see {@link https://guides.scalar.com/scalar/scalar-api-references/integrations/express}\n */\n scalarApiReferenceConfiguration?: Partial<ApiReferenceConfiguration>;\n };\n /**\n * Helps in debugging some of the variables values that are used inside arkos from dynamic loaded components towhat is used into the generated api.\n *\n */\n debugging?: {\n /**\n * Controls debugging over HTTP request level\n */\n requests?: {\n level?: 0 | 1 | 2 | 3;\n filter?: (\n | \"Query\"\n | \"Body\"\n | \"Params\"\n | \"TransformedQuery\"\n | \"ServiceArgs\"\n | \"FinalPrismaQueryArgs\"\n )[];\n };\n /**\n * Controls debugging over the dynamic loaded modules and it's components on app starting\n */\n dynamicLoader?: {\n /**\n * Adjusts logging details\n *\n * 1 - Loaded modules and list of it's components files\n * 2 - All from 1 and detailed inspection per module component\n * 3 - All from 1 and 2, plus the final router component after merged with autho generated router.\n */\n level?: 0 | 1 | 2 | 3;\n filters?: {\n /**\n * Allows filtering by specific modules.\n *\n * Supports only searching for the starting parts of the module name, e.g: If there is`user-profile`, `user`, `posts`, passing `[\"user\"]` will match both `user-profile` and `user`.\n */\n modules?: string[];\n /**\n * Allows filtering by component's names\n */\n components?: keyof ModuleComponents[];\n };\n };\n };\n};\n"]}
1
+ {"version":3,"file":"new-arkos-config.js","sourceRoot":"","sources":["../../../src/types/new-arkos-config.ts"],"names":[],"mappings":"","sourcesContent":["import cors from \"cors\";\nimport express from \"express\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport cookieParser from \"cookie-parser\";\nimport compression from \"compression\";\nimport { Options as QueryParserOptions } from \"../utils/helpers/query-parser.helpers\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { MsDuration } from \"../modules/auth/utils/helpers/auth.controller.helpers\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport type { ApiReferenceConfiguration } from \"@scalar/express-api-reference\" with { \"resolution-mode\": \"import\" };\nimport nodemailer from \"nodemailer\";\nimport { ModuleComponents } from \"../utils/dynamic-loader\";\nimport { ArkosRequestHandler } from \".\";\n\n/**\n * Defines the initial configs of the api to be loaded at startup when arkos.init() is called.\n */\nexport type ArkosConfig = {\n /**\n * Allows to configure request configs\n */\n request?: {\n /**\n * Allows to configure request parameters\n */\n parameters?: {\n /**\n * Toggles allowing `VERY DANGEROUS` request paramateres under `req.query` for passing prisma query options.\n *\n * See more\n */\n allowDangerousPrismaQueryOptions?: boolean;\n };\n };\n /** Message you would like to send, as Json and 200 response when\n * ```curl\n * GET /api\n * ```\n *\n * ```json\n * { \"message\": \"Welcome to YourAppName\" }\n * ```\n *\n * default message is: Welcome to our Rest API generated by Arkos, find more about Arkos at www.arkosjs.com.\n *\n *\n * */\n welcomeMessage?: string;\n /**\n * Port where the application will run, can be set in 3 ways:\n *\n * 1. default is 8000\n * 2. PORT under environment variables (Lower precedence)\n * 3. this config option (Higher precedence)\n */\n port?: number | undefined;\n /**\n * Allows to listen on a different host than localhost only\n */\n host?: string;\n /**\n * Defines authentication related configurations, by default is undefined.\n *\n * See [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for details.\n */\n authentication?: {\n enabled?: boolean;\n /**\n * Defines whether to use Static or Dynamic Role-Based Acess Control\n *\n * Visit [www.arkosjs.com/docs/core-concepts/authentication-system](https://www.arkosjs.com/docs/core-concepts/authentication-system) for more details.\n */\n mode: \"static\" | \"dynamic\";\n /**\n * Defines auth login related configurations to customize the api.\n */\n login?: {\n /**\n * Defines the field that will be used as username by the built-in auth system, by default arkos will look for the field \"username\" in your model User, hence when making login for example you must send:\n *\n * ```json\n * {\n * \"username\": \"johndoe\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n *\n * **Note:** You can also modify the usernameField on the fly by passing it to the request query parameters. example:\n *\n * ```curl\n * POST /api/auth/login?usernameField=email\n * ```\n *\n * See more at [www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds](https://www.arkosjs.com/docs/core-concepts/authentication-system#login-with-different-fileds)\n *\n * By specifing here another field for username, for example passing \"email\", \"companyCode\" or something else your json will be like:\n *\n * **Example with email**\n *\n * ```json\n * {\n * \"email\": \"john.doe@example.com\",\n * \"password\": \"somePassword123\"\n * }\n * ```\n */\n allowedUsernames?: string[];\n /** Defines wether to send the access token in response after login or only send as cookie, defeault is both.*/\n sendAccessTokenThrough?: \"cookie-only\" | \"response-only\" | \"both\";\n };\n /**\n * Specifies the regex pattern used by the authentication system to enforce password strength requirements.\n *\n * **Important**: If using validation libraries like Zod or class-validator, this will be completely overwritten.\n *\n * **Default**: ```/^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/``` - Ensures the password contains at least one uppercase letter, one lowercase letter, and one numeric digit.\n *\n * **message**: (Optional) A custom error message to display when the password does not meet the required strength criteria.\n */\n passwordValidation?: { regex: RegExp; message?: string };\n /**\n * Allows to specify the request rate limit for all authentication endpoints but `/api/users/me`.\n * \n * #### Default\n *{\n windowMs: 5000,\n limit: 10,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n *@see This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: Partial<RateLimitOptions>;\n /**\n * JWT (JSON Web Token) authentication configuration.\n *\n * You can override these values directly in code, or use environment variables:\n *\n * - `JWT_SECRET`: Secret used to sign and verify JWT tokens.\n * - `JWT_EXPIRES_IN`: Duration string or number indicating when the token should expire (e.g. \"30d\", 3600).\n * - `JWT_COOKIE_SECURE`: Whether the cookie is sent only over HTTPS. Default: `true` in production.\n * - `JWT_COOKIE_HTTP_ONLY`: Whether the cookie is HTTP-only. Default: `true`.\n * - `JWT_COOKIE_SAME_SITE`: Can be \"lax\", \"strict\", or \"none\". Defaults to \"lax\" in dev, \"none\" in prod.\n *\n * ⚠️ Values passed here take precedence over environment variables.\n */\n jwt?: {\n /** Secret key used for signing and verifying JWT tokens */\n secret?: string;\n /**\n * Duration after which the JWT token expires.\n * Accepts either a duration string (e.g. \"30d\", \"1h\") or a number in milliseconds.\n * Defaults to \"30d\" if not provided.\n */\n expiresIn?: MsDuration | number;\n\n /**\n * Configuration for the JWT cookie sent to the client\n */\n cookie?: {\n /**\n * Whether the cookie should be marked as secure (sent only over HTTPS).\n * Defaults to `true` in production and `false` in development.\n */\n secure?: boolean;\n\n /**\n * Whether the cookie should be marked as HTTP-only.\n * Default is `true` to prevent access via JavaScript.\n */\n httpOnly?: boolean;\n\n /**\n * Controls the SameSite attribute of the cookie.\n * Defaults to \"none\" in production and \"lax\" in development.\n * Options: \"lax\" | \"strict\" | \"none\"\n */\n sameSite?: \"lax\" | \"strict\" | \"none\";\n };\n };\n };\n /** Allows to customize and toggle the built-in validation, by default it is set to `false`. If true is passed it will use validation with the default resolver set to `class-validator` if you intend to change the resolver to `zod` do the following:\n *\n *```ts\n * // src/app.ts\n * import arkos from 'arkos'\n *\n * arkos.init({\n * validation: {\n * resolver: \"zod\"\n * }\n * })\n * ```\n *\n * @See [www.arkosjs.com/docs/core-concepts/request-data-validation](https://www.arkosjs.com/docs/core-concepts/request-data-validation) for more details.\n */\n validation?: {\n /**\n * Defines whether to use strict request validation, it means in every request using `ArkosRouter()` you must pass the validation options with all options (e.g: query, params, body, etc.).\n *\n * **How It Works:**\n * - If it is true, Arkos will require all the options a stated above on the routes and if you don't pass it will throw an error.\n * **What if you don't want to pass a validator to some options?**\n * - You will need to pass `undefined` to the validator option (see example below), this way Arkos will throw an error if something is passed to `req.query` if you passed undefined as validator into `validation.query`\n *\n * ```ts\n * import { ArkosRouter } from \"arkos\"\n *\n * const router = ArkosRouter()\n *\n * router.get({\n * route: \"/api/posts\",\n * validation: {\n * query: undefined\n * }\n * })\n *\n * ```\n */\n strict?: boolean;\n } & (\n | {\n resolver: \"class-validator\";\n /**\n * ValidatorOptions to used while validating request data.\n *\n * **Default**:\n * ```ts\n * {\n * whitelist: true\n * }\n * ```\n */\n validationOptions?: ValidatorOptions;\n }\n | {\n resolver: \"zod\";\n validationOptions?: Record<string, any>;\n }\n );\n /**\n * Defines file upload configurations\n *\n * See [www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations](https://www.arkosjs.com/docs/core-concepts/file-upload#costum-configurations)\n */\n fileUpload?: {\n /**\n * Defiens the base file upload directory, default is set to /uploads (on root directory)\n *\n * When setting up a path dir always now that root directory will be the starting reference.\n *\n * #### Example\n * passing `../my-arkos-uploaded-files`\n *\n * Will save uploaded files one level outside the root dir inside `my-arkos-uploaded-files`\n *\n * NB: You must be aware of permissions on your server to acess files outside your project directory.\n *\n */\n baseUploadDir?: string;\n /**\n * Changes the default `/api/uploads` base route for accessing file upload route.\n *\n * #### IMPORTANT\n * Changing this will not affect the `baseUploadDir` folder. You can\n * pass here `/api/files/my-user-files` and `baseUploadDir` be `/uploaded-files`.\n *\n */\n baseRoute?: string;\n /**\n * Defines options for `express.static(somePath, someOptions)`\n *\n * #### Default:\n *\n * ```ts\n *{\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n }\n * ```\n * \n * By passing your custom options have in mind that it\n * will be deepmerged with the default.\n * \n * Visit [https://expressjs.com/en/4x/api.html#express.static](https://expressjs.com/en/4x/api.html#express.static) for more understanding.\n * \n */\n expressStatic?: Parameters<typeof express.static>[1];\n /**\n * Defines upload restrictions for each file type: image, video, document or other.\n *\n * #### Important:\n * Passing an object without overriding everything will only cause it\n * to be deepmerged with the default options.\n *\n * See [www.arkosjs.com/docs/api-reference/default-supported-upload-files](https://www.arkosjs.com/docs/api-reference/default-supported-upload-files) for detailed explanation about default values.\n * ```\n */\n restrictions?: {\n images?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n videos?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n documents?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n files?: {\n maxCount?: number;\n maxSize?: number;\n supportedFilesRegex?: RegExp;\n };\n };\n };\n /**\n * Defines express middlewares configurations\n */\n middlewares?: {\n /**\n * Allows to define options for npm package compression\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/compression](https://www.npmjs.com/package/compression) for further details.\n */\n compression?: false | compression.CompressionOptions | ArkosRequestHandler;\n /**\n * Allows to specify the request rate limit for all endpoints.\n * \n * #### Default\n *```ts\n *{\n windowMs: 60 * 1000,\n limit: 1000,\n standardHeaders: \"draft-7\",\n legacyHeaders: false,\n }\n ```\n * \n * Passing an object not overriding all the default options will only\n * cause it to be deepmerged and not actually replace with empty fields\n * \n * This is are the options used on the `express-rate-limit` npm package used on epxress. read more about [https://www.npmjs.com/package/express-rate-limit](https://www.npmjs.com/package/express-rate-limit)\n */\n rateLimit?: false | Partial<RateLimitOptions> | ArkosRequestHandler;\n /**\n * Configuration for CORS (Cross-Origin Resource Sharing).\n *\n * @property {string | string[] | \"all\"} [allowedOrigins] - List of allowed origins. If set to `\"all\"`, all origins are accepted.\n * @property {import('cors').CorsOptions} [options] - Additional CORS options passed directly to the `cors` middleware.\n * @property {import('cors').CorsOptionsDelegate} [customHandler] - A custom middleware function that overrides the default behavior.\n *\n * @remarks\n * If `customHandler` is provided, both `allowedOrigins` and `options` will be ignored in favor of the custom logic.\n *\n * See https://www.npmjs.com/package/cors\n */\n cors?:\n | false\n | {\n /**\n * Defines allowed origins to acess the API.\n */\n allowedOrigins?: string | string[] | \"*\";\n options?: cors.CorsOptions;\n /**\n * If you would like to override the entire middleware\n *\n * see\n */\n customHandler?: cors.CorsOptionsDelegate;\n }\n | ArkosRequestHandler;\n /**\n * Defines options for the built-in express.json() middleware\n * Nothing is passed by default.\n */\n expressJson?:\n | false\n | Parameters<typeof express.json>[0]\n | ArkosRequestHandler;\n /**\n * Allows to pass paremeters to cookieParser from npm package cookie-parser\n * Nothing is passed by default.\n *\n * See [www.npmjs.com/package/cookie-parser](https://www.npmjs.com/package/cookie-parser) for further details.\n */\n cookieParser?:\n | false\n | Parameters<typeof cookieParser>\n | ArkosRequestHandler;\n /**\n * Options to define how query must be parsed.\n *\n * #### for example:\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n * \n * #### Default:\n * \n * {\n parseNull: true,\n parseUndefined: true,\n parseBoolean: true,\n parseNumber: true,\n }\n * \n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n * \n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParser?: false | QueryParserOptions | ArkosRequestHandler;\n /**\n * Configuration for request logger middleware.\n *\n * Logs incoming HTTP requests with details such as method, URL, status code, and response time.\n * Useful for debugging and monitoring API traffic.\n */\n requestLogger?: false | ArkosRequestHandler;\n /**\n * Configuration for global error handler middleware.\n *\n * Catches and processes errors thrown in route handlers and other middlewares.\n * Provides a centralized way to format error responses and log errors.\n */\n errorHandler?: false | express.ErrorRequestHandler;\n };\n /**\n * Defines express/arkos routers configurations\n */\n routers?: {\n /**\n * Strict mode configuration for routing security\n *\n * @default false\n * - all CRUD + Auth (if using auth) endpoits are enabled and avialable by default.\n *\n * When enabled:\n * - If `true`: All CRUD endpoints start disabled and must be explicitly enabled\n * in each model's router configuration\n * - If `'no-bulk'`: Bulk operations (createMany, updateMany, deleteMany) are disabled\n * by default, while individual operations can be enabled per model\n *\n * This provides enhanced security by ensuring no routes are accidentally exposed.\n * Use this in production environments to follow the principle of least privilege.\n *\n * See documentation: https://www.arkosjs.com/docs/guide/security#strict-mode\n */\n strict?: boolean | \"no-bulk\";\n /**\n * Replace the default welcome endpoint handler\n * @param req Express request object\n * @param res Express response object\n * @param next Express next function\n */\n welcomeRoute?: false | ArkosRequestHandler;\n };\n /**\n * Allows to configure email configurations for sending emails through `emailService`\n *\n * See [www.arkosjs.com/docs/core-concepts/sending-emails](https://www.arkosjs.com/docs/core-concepts/sending-emails)\n */\n email?: {\n /**\n * Email name to used like:\n *\n * John Doe\\<john.doe@gmail.com>\n */\n name?: string;\n /**\n * Your email provider url\n */\n host: string;\n /**\n * Email provider SMTP port, Default is `465`\n */\n port?: number;\n /**\n * If smtp connection must be secure, Default is `true`\n */\n secure?: boolean;\n /**\n * Used to authenticate in your smtp server\n */\n auth: {\n /**\n * Email used for auth as well as sending emails\n */\n user: string;\n /**\n * Your SMTP password\n */\n pass: string;\n };\n } & Parameters<typeof nodemailer.createTransport>[0];\n /**\n * Defines Swagger and OpenApi specifications for auto generating swagger documentation UI using whether it is Prisma Schemas, Class-validator DTOs, Zod Schemas or JSON-Schemas.\n *\n * **Important**: Is worth mentioning that this works alongside `@scalar/express-api-reference` npm package, you define it's ApiReferenceConfiguration under ``. also consider checking the package documentation at []\n *\n * **Usage**\n *\n * ```ts\n * // src/app.ts\n *\n * import arkos from \"arkos\"\n *\n * arkos.init({\n * // other configs\n * swagger: {\n * mode: \"zod\",\n * options: {\n * defintion: {\n * info: {\n * openapi: \"3.0.0\",\n * title: \"API Generated By Arkos.js\",\n * description: \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n * }\n * }\n * }\n * }\n * })\n * ```\n * @see {@link https://www.arkosjs.com/docs/core-concepts/swagger-api-documentation}\n */\n swagger?: {\n /**\n * By default Arkos will disable API Documentation when the project is built `npm run build`, it does not matter what node environment is set. If you want to use it even after the `arkos build` command just set this to `true`.\n * */\n enableAfterBuild?: boolean;\n /**\n * Endpoint where the Swagger UI will be available.\n *\n * @default \"/api/api-docs\"\n */\n endpoint?: string;\n /**\n * Determines how your API schemas should be generated.\n *\n * - \"prisma\": Generates schemas based on Prisma models\n * - \"class-validator\": Uses class-validator and class-transformer DTO classes\n * - \"zod\": Uses OpenAPI-compliant schemas directly\n */\n mode: \"prisma\" | \"class-validator\" | \"zod\";\n /**\n * Allows `Arkos.js` to fallback to prisma schema and use them as json schema for defining request body and response data\n * when a given zod Schema or class-validator Class is not found to be transformed to json schema.\n *\n * @default false\n */\n strict?: boolean;\n /**\n * Defines your swagger configurations\n */\n options?: {\n /**\n * Swagger definition according to OpenAPI Specification.\n */\n definition?: {\n /**\n * OpenAPI version.\n *\n * @default \"3.0.0\"\n */\n openapi?: string;\n\n /**\n * Information about your API.\n */\n info?: {\n /**\n * Title of the API documentation.\n *\n *\n * @example \"My API\"\n *\n * @default \"API Generated By Arkos.js\"\n */\n title?: string;\n\n /**\n * Version of the API.\n *\n * @example \"1.0.0\"\n */\n version?: string;\n\n /**\n * Description of the API.\n *\n * @default \"This API was automatically generated by Arkos.js read more about at www.arkosjs.com\"\n */\n description?: string;\n };\n\n /**\n * Server configurations for the API.\n *\n * @default [{ url: \"http://localhost:8000\", description: \"Development server\" }]\n *\n * This can be overridden automatically by Arkos based on CLI, .env, or `arkos.init()`.\n */\n servers?: {\n /**\n * Base URL of the server.\n *\n * @example \"http://localhost:8000\"\n */\n url: string;\n\n /**\n * Human-readable description of the server.\n *\n * @example \"Development Server\"\n */\n description?: string;\n }[];\n /**\n * Allows adding more paths for your OpenAPI documentation\n *\n * */\n paths?: OpenAPIV3.PathsObject;\n /**\n * (Optional) Additional metadata such as terms of service, contact, or license.\n *\n * See: https://swagger.io/specification/#infoObject\n */\n termsOfService?: string;\n contact?: {\n name?: string;\n url?: string;\n email?: string;\n };\n license?: {\n name: string;\n url?: string;\n };\n\n /**\n * Tags to group and describe endpoints.\n */\n tags?: {\n name: string;\n description?: string;\n }[];\n\n /**\n * Security definitions (e.g., Bearer Auth).\n */\n components?: {\n securitySchemes?: Record<string, any>;\n schemas?: Record<string, any>;\n };\n\n /**\n * Global security requirements.\n */\n security?: Array<Record<string, string[]>>;\n };\n\n /**\n * Glob patterns defining where Swagger should look for API route definitions and comments.\n *\n * @default \n * ```ts\n * [\"./src/routers/*.router.{ts,js}\", \"./src/modules/**\\/*.router.{ts,js}\"]\n ```\n *\n * Adjust depending on TypeScript or JavaScript usage.\n */\n apis?: string[];\n\n /**\n * Enables deep linking in the Swagger UI.\n *\n * @default true\n */\n deepLinking?: boolean;\n\n /**\n * Enable/disable the \"Try it out\" button globally.\n *\n * @default true\n */\n tryItOutEnabled?: boolean;\n\n /**\n * Whether to persist authorization data across page reloads.\n *\n * @default false\n */\n persistAuthorization?: boolean;\n };\n /**\n * Custom `@scalar/express-api-reference` package options.\n *\n * @see {@link https://guides.scalar.com/scalar/scalar-api-references/integrations/express}\n */\n scalarApiReferenceConfiguration?: Partial<ApiReferenceConfiguration>;\n };\n /**\n * Helps in debugging some of the variables values that are used inside arkos from dynamic loaded components towhat is used into the generated api.\n *\n */\n debugging?: {\n /**\n * Controls debugging over HTTP request level\n */\n requests?: {\n level?: 0 | 1 | 2 | 3;\n filter?: (\n | \"Query\"\n | \"Body\"\n | \"Params\"\n | \"TransformedQuery\"\n | \"ServiceArgs\"\n | \"PrismaFinalQueryArgs\"\n )[];\n };\n /**\n * Controls debugging over the dynamic loaded modules and it's components on app starting\n */\n dynamicLoader?: {\n /**\n * Adjusts logging details\n *\n * 1 - Loaded modules and list of it's components files\n * 2 - All from 1 and detailed inspection per module component\n * 3 - All from 1 and 2, plus the final router component after merged with autho generated router.\n */\n level?: 0 | 1 | 2 | 3;\n filters?: {\n /**\n * Allows filtering by specific modules.\n *\n * Supports only searching for the starting parts of the module name, e.g: If there is`user-profile`, `user`, `posts`, passing `[\"user\"]` will match both `user-profile` and `user`.\n */\n modules?: string[];\n /**\n * Allows filtering by component's names\n */\n components?: keyof ModuleComponents[];\n };\n };\n };\n};\n"]}
@@ -1,15 +1,16 @@
1
1
  import { Router } from "express";
2
2
  import RouteConfigValidator from "./route-config-validator.js";
3
3
  import RouteConfigRegistry from "./route-config-registry.js";
4
- import { extractArkosRoutes, getMiddlewareStack } from "./utils/helpers/index.js";
4
+ import { extractArkosRoutes, extractPathParams, getMiddlewareStack, } from "./utils/helpers/index.js";
5
5
  import { getArkosConfig } from "../../exports/index.js";
6
6
  import { catchAsync } from "../../exports/error-handler/index.js";
7
7
  import zodToJsonSchema from "zod-to-json-schema";
8
8
  import classValidatorToJsonSchema from "../../modules/swagger/utils/helpers/class-validator-to-json-schema.js";
9
9
  import openApiSchemaConverter from "../../modules/swagger/utils/helpers/openapi-schema-converter.js";
10
10
  import uploadManager from "./utils/helpers/upload-manager.js";
11
- export default function ArkosRouter() {
12
- const router = Router();
11
+ import { getUserFileExtension } from "../helpers/fs.helpers.js";
12
+ export default function ArkosRouter(options) {
13
+ const router = Router(options);
13
14
  return new Proxy(router, {
14
15
  get(target, prop, receiver) {
15
16
  const originalMethod = Reflect.get(target, prop, receiver);
@@ -29,20 +30,32 @@ export default function ArkosRouter() {
29
30
  if (config.disabled)
30
31
  return;
31
32
  const path = config.path;
32
- if (!path)
33
- throw Error("Please pass valid value for path field to use in your route");
34
33
  if (!RouteConfigValidator.isArkosRouteConfig(config))
35
34
  throw Error(`First argument of ArkosRouter().${prop}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === "object" ? JSON.stringify(config, null, 2) : config}`);
35
+ if ([null, undefined].includes(path))
36
+ throw Error("Please pass valid value for path field to use in your route");
36
37
  const method = prop;
38
+ const UndefinedHandlerError = (handler) => Error(`Wrong value for handler in route ${method.toUpperCase()} ${path}, recevied ${handler}.`);
37
39
  if (handlers.length > 0) {
38
40
  handlers = handlers.map((handler) => {
41
+ if (!handler)
42
+ throw UndefinedHandlerError(handler);
39
43
  return typeof handler === "function"
40
44
  ? catchAsync(handler, {
41
45
  type: handler.length > 3 ? "error" : "normal",
42
46
  })
43
- : handler.map((nesteHandler) => catchAsync(nesteHandler, {
44
- type: handler.length > 3 ? "error" : "normal",
45
- }));
47
+ : Array.isArray(handler)
48
+ ? handler.map((nesteHandler) => {
49
+ if (!handler)
50
+ throw UndefinedHandlerError(nesteHandler);
51
+ if (typeof nesteHandler === "function")
52
+ return;
53
+ catchAsync(nesteHandler, {
54
+ type: handler.length > 3 ? "error" : "normal",
55
+ });
56
+ return nesteHandler;
57
+ })
58
+ : handler;
46
59
  });
47
60
  const finalHandler = handlers[handlers.length - 1];
48
61
  RouteConfigRegistry.register(finalHandler, config, method);
@@ -61,7 +74,9 @@ export default function ArkosRouter() {
61
74
  if (!validationConfig?.resolver && config.validation)
62
75
  throw Error(`Trying to pass validators into route ${route} config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })`);
63
76
  if (config.authentication && !authenticationConfig?.mode)
64
- throw Error(`Trying to authenticate route ${route} without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })`);
77
+ throw Error(`Trying to authenticate route ${route} without choosing an authentication mode under arkos.config.${getUserFileExtension()}
78
+
79
+ For further help see https://www.arkosjs.com/docs/core-concepts/authentication-system.`);
65
80
  handlers = [...getMiddlewareStack(config), ...handlers];
66
81
  if (config.experimental?.uploads &&
67
82
  config.experimental.uploads.deleteOnError !== false)
@@ -80,6 +95,11 @@ export function generateOpenAPIFromApp(app) {
80
95
  routes.forEach(({ path, method, config }) => {
81
96
  if (config?.experimental?.openapi === false)
82
97
  return;
98
+ const originalPath = path;
99
+ const pathParatemersFromRoutePath = extractPathParams(path);
100
+ for (const parameter of pathParatemersFromRoutePath) {
101
+ path = path.replaceAll(`:${parameter}`, parameter.endsWith("?") ? `{${parameter}}?` : `{${parameter}}`);
102
+ }
83
103
  if (!paths[path])
84
104
  paths[path] = {};
85
105
  if (typeof config?.experimental?.openapi === "boolean") {
@@ -117,12 +137,32 @@ export function generateOpenAPIFromApp(app) {
117
137
  }
118
138
  }
119
139
  const convertedOpenAPI = openApiSchemaConverter.convertOpenAPIConfig(openapi);
140
+ const allParameters = [
141
+ ...(convertedOpenAPI.parameters || []),
142
+ ...parameters,
143
+ ];
144
+ for (const parameter of pathParatemersFromRoutePath) {
145
+ if (!allParameters.find(({ name, in: paramIn }) => name === parameter.replace("?", "") && paramIn === "path"))
146
+ allParameters.push({
147
+ name: parameter,
148
+ in: "path",
149
+ required: !parameter.includes("?"),
150
+ schema: { type: "string" },
151
+ });
152
+ }
153
+ for (const param of allParameters) {
154
+ if (!pathParatemersFromRoutePath.includes(param.name) &&
155
+ !pathParatemersFromRoutePath.includes(`${param.name}?`) &&
156
+ param.in === "path")
157
+ throw new Error(`ValidationError: Trying to define path parameter '${param.name}' but it is not present in your pathname ${originalPath}`);
158
+ }
159
+ delete convertedOpenAPI.parameters;
120
160
  paths[path][method.toLowerCase()] = {
121
- summary: openapi?.summary || `${method} ${path}`,
161
+ summary: openapi?.summary || `${path}`,
122
162
  description: openapi?.description || `${method} ${path}`,
123
163
  tags: openapi?.tags || ["Defaults"],
124
164
  operationId: `${method.toLowerCase()}:${path}`,
125
- parameters: [...(convertedOpenAPI.parameters || []), ...parameters],
165
+ parameters: allParameters,
126
166
  ...(!convertedOpenAPI.requestBody &&
127
167
  config?.validation &&
128
168
  config?.validation?.body && {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["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express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport { extractArkosRoutes, getMiddlewareStack } from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"../../modules/swagger/utils/helpers/class-validator-to-json-schema\";\nimport openApiSchemaConverter from \"../../modules/swagger/utils/helpers/openapi-schema-converter\";\nimport uploadManager from \"./utils/helpers/upload-manager\";\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport default function ArkosRouter(): IArkosRouter {\n const router: IArkosRouter = Router();\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n if (config.disabled) return;\n\n const path = config.path;\n\n if (!path)\n throw Error(\n \"Please pass valid value for path field to use in your route\"\n );\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n const method = prop as string;\n\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) => {\n return typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : handler.map((nesteHandler: any) =>\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n );\n }\n );\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n const strictValidation = validationConfig?.strict;\n const route = `${method.toUpperCase()} ${path}`;\n\n if (\n strictValidation &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (!validationConfig?.resolver && config.validation)\n throw Error(\n `Trying to pass validators into route ${route} config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })`\n );\n\n if (config.authentication && !authenticationConfig?.mode)\n throw Error(\n `Trying to authenticate route ${route} without choosing an authentication mode under arkos.init({ authentication: { mode: '' } })`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (\n config.experimental?.uploads &&\n config.experimental.uploads.deleteOnError !== false\n )\n handlers.push(\n catchAsync(\n uploadManager.handleFileCleanup(config.experimental.uploads),\n { type: \"error\" }\n )\n );\n\n return originalMethod.call(target, path, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n const arkosConfig = getArkosConfig();\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config }) => {\n if (config?.experimental?.openapi === false) return;\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.experimental?.openapi === \"boolean\") {\n config = {\n ...config,\n experimental: {\n ...config.experimental,\n openapi: {},\n },\n };\n }\n\n const openapi =\n typeof config?.experimental?.openapi === \"object\" &&\n config.experimental.openapi !== null\n ? config.experimental.openapi\n : {};\n\n const validatorToJsonSchema =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n let parameters = [];\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (typeof config?.validation !== \"boolean\" && config?.validation) {\n for (const [key, val] of Object.entries(config?.validation)) {\n if ([\"body\"].includes(key)) continue;\n if ((config?.validation as any)[key]) {\n const jsonSchema = validatorToJsonSchema(val as any);\n const params = openApiSchemaConverter.jsonSchemaToOpeApiParameters(\n (validationToParameterMapping as any)[key],\n jsonSchema\n );\n parameters.push(...params);\n }\n }\n }\n\n const convertedOpenAPI =\n openApiSchemaConverter.convertOpenAPIConfig(openapi);\n\n (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${method} ${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n parameters: [...(convertedOpenAPI.parameters || []), ...parameters],\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: {\n \"application/json\": {\n schema: validatorToJsonSchema(config?.validation?.body as any),\n },\n },\n },\n }),\n ...convertedOpenAPI,\n };\n });\n\n return paths;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/utils/arkos-router/index.ts"],"names":[],"mappings":"AAAA,OAAO,EA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G,MAAM,IAAI,IAAI,EAAE;YACxD,IAAI,EAAE,OAAO,EAAE,IAAI,IAAI,CAAC,UAAU,CAAC;YACnC,WAAW,EAAE,GAAG,MAAM,CAAC,WAAW,EAAE,IAAI,IAAI,EAAE;YAC9C,UAAU,EAAE,aAAa;YACzB,GAAG,CAAC,CAAC,gBAAgB,CAAC,WAAW;gBAC/B,MAAM,EAAE,UAAU;gBAClB,MAAM,EAAE,UAAU,EAAE,IAAI,IAAI;gBAC1B,WAAW,EAAE;oBACX,OAAO,EAAE;wBACP,kBAAkB,EAAE;4BAClB,MAAM,EAAE,qBAAqB,CAAC,MAAM,EAAE,UAAU,EAAE,IAAW,CAAC;yBAC/D;qBACF;iBACF;aACF,CAAC;YACJ,GAAG,gBAAgB;SACpB,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router, RouterOptions } from \"express\";\nimport { IArkosRouter, ArkosRouteConfig } from \"./types\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport RouteConfigValidator from \"./route-config-validator\";\nimport RouteConfigRegistry from \"./route-config-registry\";\nimport {\n extractArkosRoutes,\n extractPathParams,\n getMiddlewareStack,\n} from \"./utils/helpers\";\nimport { getArkosConfig } from \"../../exports\";\nimport { catchAsync } from \"../../exports/error-handler\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../types\";\nimport zodToJsonSchema from \"zod-to-json-schema\";\nimport classValidatorToJsonSchema from \"../../modules/swagger/utils/helpers/class-validator-to-json-schema\";\nimport openApiSchemaConverter from \"../../modules/swagger/utils/helpers/openapi-schema-converter\";\nimport uploadManager from \"./utils/helpers/upload-manager\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport default function ArkosRouter(options?: RouterOptions): IArkosRouter {\n const router = Router(options);\n\n return new Proxy(router, {\n get(target, prop, receiver) {\n const originalMethod = Reflect.get(target, prop, receiver);\n\n const httpMethods = [\n \"get\",\n \"post\",\n \"put\",\n \"patch\",\n \"delete\",\n \"all\",\n \"head\",\n \"trace\",\n \"options\",\n ];\n\n type ArkosAnyRequestHandler =\n | ArkosRequestHandler\n | ArkosErrorRequestHandler;\n\n if (httpMethods.includes(prop as string)) {\n return function (\n config: ArkosRouteConfig,\n ...handlers: ArkosAnyRequestHandler[]\n ) {\n if (config.disabled) return;\n\n const path = config.path;\n\n if (!RouteConfigValidator.isArkosRouteConfig(config))\n throw Error(\n `First argument of ArkosRouter().${prop as string}() must be a valid ArkosRouteConfig object with path field, but recevied ${typeof config === \"object\" ? JSON.stringify(config, null, 2) : config}`\n );\n\n if ([null, undefined].includes(path as any))\n throw Error(\n \"Please pass valid value for path field to use in your route\"\n );\n\n const method = prop as string;\n const UndefinedHandlerError = (handler: any) =>\n Error(\n `Wrong value for handler in route ${method.toUpperCase()} ${path}, recevied ${handler}.`\n );\n\n if (handlers.length > 0) {\n handlers = handlers.map(\n (handler: ArkosAnyRequestHandler | ArkosAnyRequestHandler[]) => {\n if (!handler) throw UndefinedHandlerError(handler);\n\n return typeof handler === \"function\"\n ? catchAsync(handler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n })\n : Array.isArray(handler)\n ? handler.map((nesteHandler: any) => {\n if (!handler) throw UndefinedHandlerError(nesteHandler);\n\n if (typeof nesteHandler === \"function\") return;\n catchAsync(nesteHandler, {\n type: handler.length > 3 ? \"error\" : \"normal\",\n });\n return nesteHandler;\n })\n : handler;\n }\n );\n\n const finalHandler = handlers[handlers.length - 1];\n RouteConfigRegistry.register(finalHandler, config, method);\n }\n\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const authenticationConfig = arkosConfig.authentication;\n const strictValidation = validationConfig?.strict;\n const route = `${method.toUpperCase()} ${path}`;\n\n if (\n strictValidation &&\n (!(\"validation\" in config) ||\n (\"validation\" in config &&\n !config.validation &&\n config.validation !== undefined))\n )\n throw Error(\n \"When using strict validation you must either pass { validation: false } in order to explicitly tell that no input will be received, or pass `undefined` for each input type e.g { validation: { query: undefined } } in order to deny the input of given request input.\"\n );\n\n if (!validationConfig?.resolver && config.validation)\n throw Error(\n `Trying to pass validators into route ${route} config validation option without choosing a validation resolver under arkos.init({ validation: { resolver: '' } })`\n );\n\n if (config.authentication && !authenticationConfig?.mode)\n throw Error(\n `Trying to authenticate route ${route} without choosing an authentication mode under arkos.config.${getUserFileExtension()}\n\nFor further help see https://www.arkosjs.com/docs/core-concepts/authentication-system.`\n );\n\n handlers = [...getMiddlewareStack(config), ...handlers];\n\n if (\n config.experimental?.uploads &&\n config.experimental.uploads.deleteOnError !== false\n )\n handlers.push(\n catchAsync(\n uploadManager.handleFileCleanup(config.experimental.uploads),\n { type: \"error\" }\n )\n );\n\n return originalMethod.call(target, path, ...handlers);\n };\n }\n // }\n return originalMethod;\n },\n }) as IArkosRouter;\n}\n\nexport function generateOpenAPIFromApp(app: any) {\n const routes = extractArkosRoutes(app);\n const arkosConfig = getArkosConfig();\n\n let paths: Record<\n string,\n Record<string, Partial<OpenAPIV3.OperationObject>>\n > = {};\n\n routes.forEach(({ path, method, config }) => {\n if (config?.experimental?.openapi === false) return;\n const originalPath = path;\n\n const pathParatemersFromRoutePath = extractPathParams(path);\n for (const parameter of pathParatemersFromRoutePath) {\n path = path.replaceAll(\n `:${parameter}`,\n parameter.endsWith(\"?\") ? `{${parameter}}?` : `{${parameter}}`\n );\n }\n\n if (!paths[path]) paths[path] = {};\n\n if (typeof config?.experimental?.openapi === \"boolean\") {\n config = {\n ...config,\n experimental: {\n ...config.experimental,\n openapi: {},\n },\n };\n }\n\n const openapi =\n typeof config?.experimental?.openapi === \"object\" &&\n config.experimental.openapi !== null\n ? config.experimental.openapi\n : {};\n\n const validatorToJsonSchema =\n arkosConfig?.validation?.resolver === \"zod\"\n ? zodToJsonSchema\n : classValidatorToJsonSchema;\n\n let parameters = [];\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (typeof config?.validation !== \"boolean\" && config?.validation) {\n for (const [key, val] of Object.entries(config?.validation)) {\n if ([\"body\"].includes(key)) continue;\n if ((config?.validation as any)[key]) {\n const jsonSchema = validatorToJsonSchema(val as any);\n const params = openApiSchemaConverter.jsonSchemaToOpeApiParameters(\n (validationToParameterMapping as any)[key],\n jsonSchema\n );\n parameters.push(...params);\n }\n }\n }\n\n const convertedOpenAPI =\n openApiSchemaConverter.convertOpenAPIConfig(openapi);\n\n const allParameters: OpenAPIV3.ParameterObject[] = [\n ...(convertedOpenAPI.parameters || []),\n ...parameters,\n ];\n\n for (const parameter of pathParatemersFromRoutePath) {\n if (\n !allParameters.find(\n ({ name, in: paramIn }) =>\n name === parameter.replace(\"?\", \"\") && paramIn === \"path\"\n )\n )\n allParameters.push({\n name: parameter,\n in: \"path\",\n required: !parameter.includes(\"?\"),\n schema: { type: \"string\" },\n });\n }\n\n for (const param of allParameters) {\n if (\n !pathParatemersFromRoutePath.includes(param.name) &&\n !pathParatemersFromRoutePath.includes(`${param.name}?`) &&\n param.in === \"path\"\n )\n throw new Error(\n `ValidationError: Trying to define path parameter '${param.name}' but it is not present in your pathname ${originalPath}`\n );\n }\n\n delete convertedOpenAPI.parameters;\n\n (paths as any)[path][method.toLowerCase()] = {\n summary: openapi?.summary || `${path}`,\n description: openapi?.description || `${method} ${path}`,\n tags: openapi?.tags || [\"Defaults\"],\n operationId: `${method.toLowerCase()}:${path}`,\n parameters: allParameters,\n ...(!convertedOpenAPI.requestBody &&\n config?.validation &&\n config?.validation?.body && {\n requestBody: {\n content: {\n \"application/json\": {\n schema: validatorToJsonSchema(config?.validation?.body as any),\n },\n },\n },\n }),\n ...convertedOpenAPI,\n };\n });\n\n return paths;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import { IRouter } from \"express\";\nimport { ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport { DetailedAccessControlRule } from \"../../../types/auth\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../../types\";\nimport compression from \"compression\";\nimport { OpenApiConfig } from \"./openapi-config\";\nimport { UploadConfig } from \"./upload-config\";\nimport { BodyParserConfig } from \"./body-parser-config\";\n\n/**\n * Handler function for HTTP methods that accepts route configuration and request handlers.\n *\n * @param {ArkosRouteConfig} config - The route configuration object.\n * @param {...(ArkosRequestHandler | ArkosErrorRequestHandler)[]} handlers - Request and error handlers for the route.\n * @returns {IRouter} The Express router instance.\n */\ntype MethodHandler = (\n config: ArkosRouteConfig,\n ...handlers: (ArkosRequestHandler | ArkosErrorRequestHandler)[]\n) => IRouter;\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport interface IArkosRouter\n extends Omit<\n IRouter,\n | \"get\"\n | \"post\"\n | \"put\"\n | \"patch\"\n | \"delete\"\n | \"options\"\n | \"head\"\n | \"trace\"\n | \"all\"\n > {\n /** GET method handler with route configuration support */\n get: MethodHandler;\n /** POST method handler with route configuration support */\n post: MethodHandler;\n /** PUT method handler with route configuration support */\n put: MethodHandler;\n /** PATCH method handler with route configuration support */\n patch: MethodHandler;\n /** DELETE method handler with route configuration support */\n delete: MethodHandler;\n /** OPTIONS method handler with route configuration support */\n options: MethodHandler;\n /** HEAD method handler with route configuration support */\n head: MethodHandler;\n /** TRACE method handler with route configuration support */\n trace: MethodHandler;\n /** ALL methods handler with route configuration support */\n all: MethodHandler;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport interface ArkosRouteConfig {\n /**\n * Disables the route by not mounting it internally.\n */\n disabled?: boolean;\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n path: string;\n /**\n * Authentication and authorization configuration.\n *\n * @remarks\n * - Set to `true` to require authentication without specific permissions.\n * - Set to `false` or omit to allow unauthenticated access.\n * - Provide an object to specify resource-based access control with resource name, action, and optional custom rules.\n */\n authentication?:\n | boolean\n | {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[];\n };\n /**\n * Request validation configuration using Zod schemas or class constructors.\n *\n * @remarks\n * - Set to `false` to disable all validation.\n * - Provide an object with `query`, `body`, and/or `params` properties to validate specific parts of the request.\n * - Each property accepts a Zod schema, a class constructor, or `false` to disable validation for that part.\n */\n validation?:\n | false\n | {\n query?: ZodSchema | (new (...args: any[]) => object) | false;\n body?: ZodSchema | (new (...args: any[]) => object) | false;\n params?: ZodSchema | (new (...args: any[]) => object) | false;\n };\n\n /**\n * Rate limiting configuration for this route.\n *\n * @see {@link https://www.npmjs.com/package/express-rate-limit express-rate-limit} for available options.\n */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Allows to define options for npm package compression.\n * Nothing is passed by default.\n *\n * @see {@link https://www.npmjs.com/package/compression compression} for further details.\n */\n compression?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * @example\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n *\n * @default\n * ```\n * {\n * parseNull: true,\n * parseUndefined: true,\n * parseBoolean: true,\n * }\n * ```\n *\n * @remarks\n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n *\n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParser?: QueryParserOptions;\n /**\n * Configuration for request body parsing.\n *\n * @property {(\"json\" | \"urlencoded\" | \"raw\" | \"text\")} parser - The type of body parser to use.\n * @property {object} [options] - Parser-specific options passed to the corresponding Express body parser middleware.\n *\n * @remarks\n * - When `parser` is `\"json\"`, options are passed to `express.json()`.\n * - When `parser` is `\"urlencoded\"`, options are passed to `express.urlencoded()`.\n * - When `parser` is `\"raw\"`, options are passed to `express.raw()`.\n * - When `parser` is `\"text\"`, options are passed to `express.text()`.\n * - Set to `false` to disable body parsing for this route.\n *\n * @see {@link https://expressjs.com/en/api.html#express.json Express body parser documentation}\n */\n bodyParser?: BodyParserConfig | BodyParserConfig[] | false;\n /**\n * Experimental features to be battled tested before being stable\n *\n * PS: These features may be changed without any previous warning.\n */\n experimental?: {\n /**\n * OpenAPI specification for this route.\n *\n * @remarks\n * - Set to `false` to exclude this route from OpenAPI documentation.\n * - Provide a partial OpenAPI operation object to document the route.\n */\n openapi?: false | OpenApiConfig;\n /**\n * Configuration for file upload handling in routes.\n * Supports single file, multiple files from same field, or multiple fields with files.\n */\n uploads?: UploadConfig;\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/utils/arkos-router/types/index.ts"],"names":[],"mappings":"","sourcesContent":["import { IRouter } from \"express\";\nimport { ZodSchema } from \"zod\";\nimport { Options as RateLimitOptions } from \"express-rate-limit\";\nimport { Options as QueryParserOptions } from \"../../../utils/helpers/query-parser.helpers\";\nimport { DetailedAccessControlRule } from \"../../../types/auth\";\nimport { ArkosErrorRequestHandler, ArkosRequestHandler } from \"../../../types\";\nimport compression from \"compression\";\nimport { OpenApiConfig } from \"./openapi-config\";\nimport { UploadConfig } from \"./upload-config\";\nimport { BodyParserConfig } from \"./body-parser-config\";\n\nexport type PathParams = string | RegExp | Array<string | RegExp>;\n\n/**\n * Handler function for HTTP methods that accepts route configuration and request handlers.\n *\n * @param {ArkosRouteConfig} config - The route configuration object.\n * @param {...(ArkosRequestHandler | ArkosErrorRequestHandler)[]} handlers - Request and error handlers for the route.\n * @returns {IRouter} The Express router instance.\n */\ntype MethodHandler<T> = (\n config: ArkosRouteConfig | PathParams,\n ...handlers: Array<\n | ArkosRequestHandler\n | ArkosErrorRequestHandler\n | Array<ArkosRequestHandler | ArkosErrorRequestHandler>\n >\n) => T;\n\n/**\n * Creates an enhanced Express Router with features like OpenAPI documentation capabilities and smart data validation.\n *\n * The ArkosRouter extends the standard Express Router with the ability to\n * automatically capture OpenAPI metadata from route configurations.\n *\n * @example\n * const router = ArkosRouter();\n *\n * router.get(\n * {\n * path: \"/users/:id\",\n * openapi: {\n * summary: \"Get user by ID\",\n * tags: [\"Users\"]\n * }\n * },\n * (req, res) => { ... }\n * );\n *\n * @returns {IArkosRouter} A proxied Express Router instance with enhanced OpenAPI capabilities\n *\n * @see {@link ArkosRouteConfig} for configuration options\n */\nexport interface IArkosRouter extends IRouter {\n /** GET method handler with route configuration support */\n get: MethodHandler<this>;\n /** POST method handler with route configuration support */\n post: MethodHandler<this>;\n /** PUT method handler with route configuration support */\n put: MethodHandler<this>;\n /** PATCH method handler with route configuration support */\n patch: MethodHandler<this>;\n /** DELETE method handler with route configuration support */\n delete: MethodHandler<this>;\n /** OPTIONS method handler with route configuration support */\n options: MethodHandler<this>;\n /** HEAD method handler with route configuration support */\n head: MethodHandler<this>;\n // /** TRACE method handler with route configuration support */\n trace: MethodHandler<this>;\n /** ALL methods handler with route configuration support */\n all: MethodHandler<this>;\n}\n\n/**\n * Configuration object for defining routes in Arkos.js.\n */\nexport type ArkosRouteConfig = {\n /**\n * Disables the route by not mounting it internally.\n */\n disabled?: boolean;\n /**\n * The URL path pattern for the route.\n *\n * @example \"/api/users/:id\"\n */\n path: PathParams;\n /**\n * Authentication and authorization configuration.\n *\n * @remarks\n * - Set to `true` to require authentication without specific permissions.\n * - Set to `false` or omit to allow unauthenticated access.\n * - Provide an object to specify resource-based access control with resource name, action, and optional custom rules.\n */\n authentication?:\n | boolean\n | {\n resource: string;\n action: string;\n rule?: DetailedAccessControlRule | string[];\n };\n /**\n * Request validation configuration using Zod schemas or class constructors.\n *\n * @remarks\n * - Set to `false` to disable all validation.\n * - Provide an object with `query`, `body`, and/or `params` properties to validate specific parts of the request.\n * - Each property accepts a Zod schema, a class constructor, or `false` to disable validation for that part.\n */\n validation?:\n | false\n | {\n query?: ZodSchema | (new (...args: any[]) => object) | false;\n body?: ZodSchema | (new (...args: any[]) => object) | false;\n params?: ZodSchema | (new (...args: any[]) => object) | false;\n };\n\n /**\n * Rate limiting configuration for this route.\n *\n * @see {@link https://www.npmjs.com/package/express-rate-limit express-rate-limit} for available options.\n */\n rateLimit?: Partial<RateLimitOptions>;\n\n /**\n * Allows to define options for npm package compression.\n * Nothing is passed by default.\n *\n * @see {@link https://www.npmjs.com/package/compression compression} for further details.\n */\n compression?: compression.CompressionOptions;\n /**\n * Options to define how query must be parsed.\n *\n * @example\n * ```\n * GET /api/product?saleId=null\n * ```\n *\n * Normally would parsed to { saleId: \"null\" } so query parser\n * trough setting option `parseNull` will transform { saleId: null }\n *\n * @default\n * ```\n * {\n * parseNull: true,\n * parseUndefined: true,\n * parseBoolean: true,\n * }\n * ```\n *\n * @remarks\n * parseNumber may convert fields that are string but you only passed\n * numbers to query pay attention to this.\n *\n * Soon a feature to converted the query to the end prisma type will be added.\n */\n queryParser?: QueryParserOptions;\n /**\n * Configuration for request body parsing.\n *\n * @property {(\"json\" | \"urlencoded\" | \"raw\" | \"text\")} parser - The type of body parser to use.\n * @property {object} [options] - Parser-specific options passed to the corresponding Express body parser middleware.\n *\n * @remarks\n * - When `parser` is `\"json\"`, options are passed to `express.json()`.\n * - When `parser` is `\"urlencoded\"`, options are passed to `express.urlencoded()`.\n * - When `parser` is `\"raw\"`, options are passed to `express.raw()`.\n * - When `parser` is `\"text\"`, options are passed to `express.text()`.\n * - Set to `false` to disable body parsing for this route.\n *\n * @see {@link https://expressjs.com/en/api.html#express.json Express body parser documentation}\n */\n bodyParser?: BodyParserConfig | BodyParserConfig[] | false;\n /**\n * Experimental features to be battled tested before being stable\n *\n * PS: These features may be changed without any previous warning.\n */\n experimental?: {\n /**\n * OpenAPI specification for this route.\n *\n * @remarks\n * - Set to `false` to exclude this route from OpenAPI documentation.\n * - Provide a partial OpenAPI operation object to document the route.\n */\n openapi?: false | OpenApiConfig;\n /**\n * Configuration for file upload handling in routes.\n * Supports single file, multiple files from same field, or multiple fields with files.\n */\n uploads?: UploadConfig;\n };\n};\n"]}
@@ -89,4 +89,14 @@ export function getMiddlewareStack(config) {
89
89
  middlewares.push(validateRequestInputs(config));
90
90
  return middlewares;
91
91
  }
92
+ export function extractPathParams(path) {
93
+ const params = [];
94
+ const segments = path.split("/");
95
+ for (const segment of segments) {
96
+ if (segment.startsWith(":")) {
97
+ params.push(segment.substring(1));
98
+ }
99
+ }
100
+ return params;
101
+ }
92
102
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/helpers/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,oBAAoB,CAAC;AAC3C,OAAO,WAAW,MAAM,uCAAuC,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,mBAAmB,MAAM,6BAA6B,CAAC;AAE9D,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,WAAW,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM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Y,CAAC,OAAO,CAAC,CAAC,CAAC;QAE1E,WAAW,CAAC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC,CAAC;QAEhD,WAAW,CAAC,IAAI,CACd,aAAa,CAAC,gBAAgB,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAC5D,CAAC;IACJ,CAAC;;QAAM,WAAW,CAAC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC,CAAC;IAEvD,OAAO,WAAW,CAAC;AACrB,CAAC","sourcesContent":["import rateLimit from \"express-rate-limit\";\nimport authService from \"../../../../modules/auth/auth.service\";\nimport { validateRequestInputs } from \"../../../../modules/base/base.middlewares\";\nimport RouteConfigRegistry from \"../../route-config-registry\";\nimport { ArkosRouteConfig } from \"../../types\";\nimport express from \"express\";\nimport compression from \"compression\";\nimport { queryParser } from \"../../../helpers/query-parser.helpers\";\nimport uploadManager from \"./upload-manager\";\nimport multer from \"multer\";\nimport { catchAsync } from \"../../../../exports/error-handler\";\n\nexport function extractArkosRoutes(\n app: any,\n basePath = \"\"\n): Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n}> {\n const routes: Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n }> = [];\n\n function extractFromStack(stack: any[], prefix = \"\") {\n stack.forEach((layer: any) => {\n if (layer.route) {\n const fullPath = prefix + layer.route.path;\n const methods = Object.keys(layer.route.methods);\n\n methods.forEach((method) => {\n const handlers = layer.route.stack || [];\n let config: ArkosRouteConfig | undefined;\n\n for (const handler of handlers) {\n const foundConfig = RouteConfigRegistry.get(handler.handle);\n\n if (foundConfig) {\n config = foundConfig;\n routes.push({\n path: fullPath,\n method: method.toUpperCase(),\n config,\n });\n\n break;\n }\n }\n });\n } else if (layer.name === \"router\" && layer.handle?.stack) {\n let nestedPrefix = prefix;\n\n if (layer.regexp) {\n const match = layer.regexp\n .toString()\n .match(/\\/\\^?(\\\\\\/[^?]+|\\/[^?]+)/);\n if (match) {\n nestedPrefix = prefix + \"/\" + match[1].replace(/\\\\\\//g, \"/\");\n nestedPrefix = nestedPrefix\n .replace(/\\/\\//g, \"/\")\n .replace(/\\/$/, \"\");\n }\n }\n\n extractFromStack(layer.handle.stack, nestedPrefix);\n }\n });\n }\n\n const stack = app._router?.stack || app.stack;\n if (stack) extractFromStack(stack, basePath);\n\n return routes;\n}\n\nexport function getMiddlewareStack(config: ArkosRouteConfig) {\n const middlewares = [];\n\n if (config.authentication) middlewares.push(authService.authenticate);\n\n if (\n typeof config.authentication === \"object\" &&\n config.authentication.action &&\n config.authentication.resource\n )\n middlewares.push(\n authService.handleAccessControl(\n config.authentication.action,\n config.authentication.resource,\n { [config.authentication.action]: config.authentication?.rule }\n )\n );\n\n if (config.rateLimit) middlewares.push(rateLimit(config.rateLimit));\n if (config.compression) middlewares.push(compression(config.compression));\n if (config.queryParser) middlewares.push(queryParser(config.queryParser));\n\n if (config?.bodyParser) {\n const parsers = Array.isArray(config.bodyParser)\n ? config.bodyParser\n : [config.bodyParser];\n\n parsers.forEach((parser) => {\n if (typeof parser === \"object\" && parser.parser)\n if (parser.parser !== \"multipart\")\n middlewares.push(catchAsync(express[parser.parser](parser.options)));\n else if (parser.parser === \"multipart\")\n middlewares.push(\n catchAsync(multer({ limits: parser.options }).none())\n );\n });\n }\n\n if (config.experimental?.uploads) {\n middlewares.push(uploadManager.handleUpload(config.experimental.uploads));\n\n middlewares.push(validateRequestInputs(config));\n\n middlewares.push(\n uploadManager.handlePostUpload(config.experimental.uploads)\n );\n } else middlewares.push(validateRequestInputs(config));\n\n return middlewares;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/utils/arkos-router/utils/helpers/index.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,oBAAoB,CAAC;AAC3C,OAAO,WAAW,MAAM,uCAAuC,CAAC;AAChE,OAAO,EAAE,qBAAqB,EAAE,MAAM,2CAA2C,CAAC;AAClF,OAAO,mBAAmB,MA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AAC;IAED,IAAI,MAAM,CAAC,YAAY,EAAE,OAAO,EAAE,CAAC;QACjC,WAAW,CAAC,IAAI,CAAC,aAAa,CAAC,YAAY,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC;QAE1E,WAAW,CAAC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC,CAAC;QAEhD,WAAW,CAAC,IAAI,CACd,aAAa,CAAC,gBAAgB,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAC5D,CAAC;IACJ,CAAC;;QAAM,WAAW,CAAC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC,CAAC;IAEvD,OAAO,WAAW,CAAC;AACrB,CAAC;AAaD,MAAM,UAAU,iBAAiB,CAAC,IAAY;IAC5C,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAEjC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAC/B,IAAI,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;YAC5B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC;QACpC,CAAC;IACH,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import rateLimit from \"express-rate-limit\";\nimport authService from \"../../../../modules/auth/auth.service\";\nimport { validateRequestInputs } from \"../../../../modules/base/base.middlewares\";\nimport RouteConfigRegistry from \"../../route-config-registry\";\nimport { ArkosRouteConfig } from \"../../types\";\nimport express from \"express\";\nimport compression from \"compression\";\nimport { queryParser } from \"../../../helpers/query-parser.helpers\";\nimport uploadManager from \"./upload-manager\";\nimport multer from \"multer\";\nimport { catchAsync } from \"../../../../exports/error-handler\";\n\nexport function extractArkosRoutes(\n app: any,\n basePath = \"\"\n): Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n}> {\n const routes: Array<{\n path: string;\n method: string;\n config?: ArkosRouteConfig;\n }> = [];\n\n function extractFromStack(stack: any[], prefix = \"\") {\n stack.forEach((layer: any) => {\n if (layer.route) {\n const fullPath = prefix + layer.route.path;\n const methods = Object.keys(layer.route.methods);\n\n methods.forEach((method) => {\n const handlers = layer.route.stack || [];\n let config: ArkosRouteConfig | undefined;\n\n for (const handler of handlers) {\n const foundConfig = RouteConfigRegistry.get(handler.handle);\n\n if (foundConfig) {\n config = foundConfig;\n routes.push({\n path: fullPath,\n method: method.toUpperCase(),\n config,\n });\n\n break;\n }\n }\n });\n } else if (layer.name === \"router\" && layer.handle?.stack) {\n let nestedPrefix = prefix;\n\n if (layer.regexp) {\n const match = layer.regexp\n .toString()\n .match(/\\/\\^?(\\\\\\/[^?]+|\\/[^?]+)/);\n if (match) {\n nestedPrefix = prefix + \"/\" + match[1].replace(/\\\\\\//g, \"/\");\n nestedPrefix = nestedPrefix\n .replace(/\\/\\//g, \"/\")\n .replace(/\\/$/, \"\");\n }\n }\n\n extractFromStack(layer.handle.stack, nestedPrefix);\n }\n });\n }\n\n const stack = app._router?.stack || app.stack;\n if (stack) extractFromStack(stack, basePath);\n\n return routes;\n}\n\nexport function getMiddlewareStack(config: ArkosRouteConfig) {\n const middlewares = [];\n\n if (config.authentication) middlewares.push(authService.authenticate);\n\n if (\n typeof config.authentication === \"object\" &&\n config.authentication.action &&\n config.authentication.resource\n )\n middlewares.push(\n authService.handleAccessControl(\n config.authentication.action,\n config.authentication.resource,\n { [config.authentication.action]: config.authentication?.rule }\n )\n );\n\n if (config.rateLimit) middlewares.push(rateLimit(config.rateLimit));\n if (config.compression) middlewares.push(compression(config.compression));\n if (config.queryParser) middlewares.push(queryParser(config.queryParser));\n\n if (config?.bodyParser) {\n const parsers = Array.isArray(config.bodyParser)\n ? config.bodyParser\n : [config.bodyParser];\n\n parsers.forEach((parser) => {\n if (typeof parser === \"object\" && parser.parser)\n if (parser.parser !== \"multipart\")\n middlewares.push(catchAsync(express[parser.parser](parser.options)));\n else if (parser.parser === \"multipart\")\n middlewares.push(\n catchAsync(multer({ limits: parser.options }).none())\n );\n });\n }\n\n if (config.experimental?.uploads) {\n middlewares.push(uploadManager.handleUpload(config.experimental.uploads));\n\n middlewares.push(validateRequestInputs(config));\n\n middlewares.push(\n uploadManager.handlePostUpload(config.experimental.uploads)\n );\n } else middlewares.push(validateRequestInputs(config));\n\n return middlewares;\n}\n\n/**\n * Extracts path parameters from an Express route path\n *\n * @param path - Express route path with :param syntax\n * @returns Array of parameter names\n *\n * @example\n * extractPathParams('/api/users/:userId/posts/:postId')\n * // => ['userId', 'postId']\n *\n */\nexport function extractPathParams(path: string): string[] {\n const params: string[] = [];\n const segments = path.split(\"/\");\n\n for (const segment of segments) {\n if (segment.startsWith(\":\")) {\n params.push(segment.substring(1));\n }\n }\n\n return params;\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  import { spawn, execSync } from "child_process";
2
- import chokidar from "chokidar";
3
- import { fullCleanCwd, getUserFileExtension } from "../helpers/fs.helpers.js";
2
+ import { getUserFileExtension } from "../helpers/fs.helpers.js";
4
3
  import { loadEnvironmentVariables } from "../dotenv.helpers.js";
5
4
  import fs from "fs";
6
5
  import path from "path";
@@ -10,7 +9,7 @@ import watermarkStamper from "./utils/watermark-stamper.js";
10
9
  let child = null;
11
10
  let envFiles;
12
11
  export async function devCommand(options = {}) {
13
- if (process.env.NODE_ENV === "test" || !process.env.NODE_ENV)
12
+ if (!process.env.NODE_ENV)
14
13
  process.env.NODE_ENV = "development";
15
14
  envFiles = loadEnvironmentVariables();
16
15
  child = null;
@@ -18,18 +17,17 @@ export async function devCommand(options = {}) {
18
17
  try {
19
18
  const { port, host } = options;
20
19
  let isRestarting = false;
21
- let restartingFiles = new Set();
22
20
  const fileExt = getUserFileExtension();
23
21
  const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);
24
22
  if (!fs.existsSync(entryPoint)) {
25
23
  console.error(`Could not find application entry point at ${entryPoint}`);
26
- process.exit(1);
24
+ return process.exit(1);
27
25
  }
28
26
  const baseServiceTypesPath = path.resolve(process.cwd(), `node_modules/@arkosjs/types/base.service.d.ts`);
29
27
  if (fileExt === "ts" && !fs.existsSync(baseServiceTypesPath)) {
30
28
  const answer = await new Promise((resolve) => {
31
- sheu.info('Missing base services types please run "npx arkos prisma generate" to generate and sync the types from @prisma/client');
32
- process.stdout.write(`\n${sheu.green("?", { bold: true })}Would you like to run "npx arkos prisma generate"? (Y/n): `);
29
+ sheu.warn('Missing base services types please run "npx arkos prisma generate" to generate and sync the types from @prisma/client');
30
+ process.stdout.write(`\n${sheu.green("?", { bold: true })} Would you like to run "npx arkos prisma generate"? (Y/n): `);
33
31
  process.stdin.once("data", (data) => {
34
32
  const result = data.toString().trim().toLowerCase();
35
33
  process.stdin.pause();
@@ -38,8 +36,8 @@ export async function devCommand(options = {}) {
38
36
  });
39
37
  if (answer) {
40
38
  console.info("\nSyncing base service with @prisma/client...");
41
- execSync(`npx arkos prisma generate`);
42
39
  console.log("");
40
+ execSync(`npx arkos prisma generate`);
43
41
  }
44
42
  else
45
43
  throw Error('Missing BaseService types please run "npx arkos prisma generate" to generate and sync the types from @prisma/client, see more at https://www.arkosjs.com/docs/cli/built-in-cli#typescript-types-generation.');
@@ -51,6 +49,14 @@ export async function devCommand(options = {}) {
51
49
  ...(host && { CLI_HOST: host }),
52
50
  CLI: "false",
53
51
  });
52
+ const env = getEnv();
53
+ const hostAndPort = await portAndHostAllocator.getHostAndAvailablePort(env, { logWarning: true });
54
+ watermarkStamper.stamp({
55
+ ...hostAndPort,
56
+ envFiles,
57
+ });
58
+ process.env.__PORT = hostAndPort.port || "";
59
+ process.env.__HOST = hostAndPort.host || "";
54
60
  const startServer = () => {
55
61
  if (child) {
56
62
  child.kill();
@@ -83,58 +89,10 @@ export async function devCommand(options = {}) {
83
89
  });
84
90
  }
85
91
  };
86
- const scheduleRestart = (reason, filePath) => {
87
- if (filePath)
88
- restartingFiles.add(filePath);
89
- if (restartTimeout)
90
- clearTimeout(restartTimeout);
91
- const now = new Date();
92
- const time = now.toTimeString().split(" ")[0];
93
- isRestarting = true;
94
- if (child) {
95
- child.kill();
96
- child = null;
97
- }
98
- restartTimeout = setTimeout(() => {
99
- sheu.info(`\x1b[90m${time}\x1b[0m Restarting: ${reason.toLowerCase()}`);
100
- startServer();
101
- isRestarting = false;
102
- restartTimeout = null;
103
- if (filePath)
104
- restartingFiles.delete(filePath);
105
- }, 1000);
106
- };
107
- const setupEnvWatcher = () => {
108
- const envWatcher = chokidar.watch(fullCleanCwd(envFiles?.join(",") || "")
109
- .replaceAll("/", "")
110
- .split(",") || [], {
111
- ignoreInitial: true,
112
- persistent: true,
113
- });
114
- envWatcher.on("all", (_, filePath) => {
115
- try {
116
- envFiles = loadEnvironmentVariables();
117
- scheduleRestart("Environment files changed", "env-files");
118
- }
119
- catch (error) {
120
- console.error(`Error reloading ${filePath}:`, error);
121
- }
122
- });
123
- return envWatcher;
124
- };
125
92
  startServer();
126
- const envWatcher = setupEnvWatcher();
127
- const env = getEnv();
128
- const hostAndPort = await portAndHostAllocator.getHostAndAvailablePort(env, { logWarning: true });
129
- watermarkStamper.stamp({
130
- ...hostAndPort,
131
- envFiles,
132
- });
133
93
  const cleanup = () => {
134
94
  if (restartTimeout)
135
95
  clearTimeout(restartTimeout);
136
- if (envWatcher)
137
- envWatcher.close();
138
96
  if (child) {
139
97
  child.kill("SIGTERM");
140
98
  setTimeout(() => {
@@ -1 +1 @@
1
- {"version":3,"file":"dev.js","sourceRoot":"","sources":["../../../../src/utils/cli/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAgB,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,QAAQ,MAAM,UAAU,CAAC;AAChC,OAAO,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC7D,OA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AAE,CAAC;QACf,IAAI,CAAC,KAAK,CAAC,qCAAqC,CAAC,CAAC;QAClD,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAErB,IAAI,KAAK,EAAE,CAAC;YACT,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;YAClC,KAAK,GAAG,IAAI,CAAC;QACf,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,MAAM,UAAU,iCAAiC;IAC9C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import { spawn, ChildProcess, execSync } from \"child_process\";\nimport chokidar from \"chokidar\";\nimport { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport sheu from \"../sheu\";\nimport portAndHostAllocator from \"../features/port-and-host-allocator\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\n\ninterface DevOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Dev server command for the arkos CLI\n */\nexport async function devCommand(options: DevOptions = {}) {\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"development\";\n envFiles = loadEnvironmentVariables();\n child = null;\n let restartTimeout: NodeJS.Timeout | null = null;\n\n try {\n const { port, host } = options;\n let isRestarting = false;\n let restartingFiles = new Set<string>();\n\n const fileExt = getUserFileExtension();\n const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);\n\n if (!fs.existsSync(entryPoint)) {\n console.error(`Could not find application entry point at ${entryPoint}`);\n process.exit(1);\n }\n\n const baseServiceTypesPath = path.resolve(\n process.cwd(),\n `node_modules/@arkosjs/types/base.service.d.ts`\n );\n if (fileExt === \"ts\" && !fs.existsSync(baseServiceTypesPath)) {\n const answer = await new Promise<boolean>((resolve) => {\n sheu.info(\n 'Missing base services types please run \"npx arkos prisma generate\" to generate and sync the types from @prisma/client'\n );\n process.stdout.write(\n `\\n${sheu.green(\"?\", { bold: true })}Would you like to run \"npx arkos prisma generate\"? (Y/n): `\n );\n process.stdin.once(\"data\", (data) => {\n const result = data.toString().trim().toLowerCase();\n process.stdin.pause();\n resolve(result === \"y\" || result.length === 0);\n });\n });\n\n if (answer) {\n console.info(\"\\nSyncing base service with @prisma/client...\");\n execSync(`npx arkos prisma generate`);\n console.log(\"\");\n } else\n throw Error(\n 'Missing BaseService types please run \"npx arkos prisma generate\" to generate and sync the types from @prisma/client, see more at https://www.arkosjs.com/docs/cli/built-in-cli#typescript-types-generation.'\n );\n }\n\n const getEnv = () =>\n ({\n NODE_ENV: \"development\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n CLI: \"false\",\n }) as { [x: string]: string };\n\n const startServer = () => {\n if (child) {\n child.kill();\n child = null;\n }\n\n const env = getEnv();\n\n if (fileExt === \"ts\") {\n child = spawn(\"npx\", [\"tsx-strict\", \"--watch\", entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n } else {\n child = spawn(\n \"npx\",\n [\"tsx-strict\", \"--no-type-check\", \"--watch\", entryPoint],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n }\n\n if (child) {\n child.on(\"error\", (error) => {\n console.error(\"Failed to start server:\", error);\n });\n\n child.on(\"exit\", (code, signal) => {\n if (!isRestarting && signal !== \"SIGTERM\" && signal !== \"SIGINT\") {\n console.info(`Server exited with code ${code}, restarting...`);\n startServer();\n }\n });\n }\n };\n\n const scheduleRestart = (reason: string, filePath?: string) => {\n if (filePath) restartingFiles.add(filePath);\n\n if (restartTimeout) clearTimeout(restartTimeout);\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n isRestarting = true;\n if (child) {\n child.kill();\n child = null;\n }\n\n restartTimeout = setTimeout(() => {\n sheu.info(`\\x1b[90m${time}\\x1b[0m Restarting: ${reason.toLowerCase()}`);\n startServer();\n isRestarting = false;\n restartTimeout = null;\n if (filePath) restartingFiles.delete(filePath);\n }, 1000);\n };\n\n const setupEnvWatcher = () => {\n const envWatcher = chokidar.watch(\n fullCleanCwd(envFiles?.join(\",\") || \"\")\n .replaceAll(\"/\", \"\")\n .split(\",\") || [],\n {\n ignoreInitial: true,\n persistent: true,\n }\n );\n\n envWatcher.on(\"all\", (_, filePath) => {\n try {\n envFiles = loadEnvironmentVariables();\n scheduleRestart(\"Environment files changed\", \"env-files\");\n } catch (error) {\n console.error(`Error reloading ${filePath}:`, error);\n }\n });\n\n return envWatcher;\n };\n\n startServer();\n\n const envWatcher = setupEnvWatcher();\n\n const env = getEnv();\n const hostAndPort = await portAndHostAllocator.getHostAndAvailablePort(\n env,\n { logWarning: true }\n );\n\n watermarkStamper.stamp({\n ...hostAndPort,\n envFiles,\n });\n\n const cleanup = () => {\n if (restartTimeout) clearTimeout(restartTimeout);\n\n if (envWatcher) envWatcher.close();\n\n if (child) {\n child.kill(\"SIGTERM\");\n\n setTimeout(() => {\n if (child && !child.killed) child.kill(\"SIGKILL\");\n }, 5000);\n }\n\n process.exit(0);\n };\n\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n process.on(\"uncaughtException\", (error) => {\n console.error(\"Uncaught Exception:\", error);\n cleanup();\n });\n } catch (error) {\n sheu.error(\"Development server failed to start:\");\n console.error(error);\n\n if (child) {\n (child as ChildProcess)?.kill?.();\n child = null;\n }\n\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the development server child process\n */\nexport function killDevelopmentServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
1
+ {"version":3,"file":"dev.js","sourceRoot":"","sources":["../../../../src/utils/cli/dev.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAgB,QAAQ,EAAE,MAAM,eAAe,CAA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AC;QACf,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,MAAM,UAAU,iCAAiC;IAC9C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import { spawn, ChildProcess, execSync } from \"child_process\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport sheu from \"../sheu\";\nimport portAndHostAllocator from \"../features/port-and-host-allocator\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\n\ninterface DevOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Dev server command for the arkos CLI\n */\nexport async function devCommand(options: DevOptions = {}) {\n if (!process.env.NODE_ENV) process.env.NODE_ENV = \"development\";\n envFiles = loadEnvironmentVariables();\n child = null;\n let restartTimeout: NodeJS.Timeout | null = null;\n\n try {\n const { port, host } = options;\n let isRestarting = false;\n\n const fileExt = getUserFileExtension();\n const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);\n\n if (!fs.existsSync(entryPoint)) {\n console.error(`Could not find application entry point at ${entryPoint}`);\n return process.exit(1);\n }\n\n const baseServiceTypesPath = path.resolve(\n process.cwd(),\n `node_modules/@arkosjs/types/base.service.d.ts`\n );\n if (fileExt === \"ts\" && !fs.existsSync(baseServiceTypesPath)) {\n const answer = await new Promise<boolean>((resolve) => {\n sheu.warn(\n 'Missing base services types please run \"npx arkos prisma generate\" to generate and sync the types from @prisma/client'\n );\n process.stdout.write(\n `\\n${sheu.green(\"?\", { bold: true })} Would you like to run \"npx arkos prisma generate\"? (Y/n): `\n );\n process.stdin.once(\"data\", (data) => {\n const result = data.toString().trim().toLowerCase();\n process.stdin.pause();\n resolve(result === \"y\" || result.length === 0);\n });\n });\n\n if (answer) {\n console.info(\"\\nSyncing base service with @prisma/client...\");\n console.log(\"\");\n execSync(`npx arkos prisma generate`);\n } else\n throw Error(\n 'Missing BaseService types please run \"npx arkos prisma generate\" to generate and sync the types from @prisma/client, see more at https://www.arkosjs.com/docs/cli/built-in-cli#typescript-types-generation.'\n );\n }\n\n const getEnv = () =>\n ({\n NODE_ENV: \"development\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n CLI: \"false\",\n }) as { [x: string]: string };\n\n const env = getEnv();\n const hostAndPort = await portAndHostAllocator.getHostAndAvailablePort(\n env,\n { logWarning: true }\n );\n\n watermarkStamper.stamp({\n ...hostAndPort,\n envFiles,\n });\n\n process.env.__PORT = hostAndPort.port || \"\";\n process.env.__HOST = hostAndPort.host || \"\";\n\n const startServer = () => {\n if (child) {\n child.kill();\n child = null;\n }\n\n const env = getEnv();\n\n if (fileExt === \"ts\") {\n child = spawn(\"npx\", [\"tsx-strict\", \"--watch\", entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n } else {\n child = spawn(\n \"npx\",\n [\"tsx-strict\", \"--no-type-check\", \"--watch\", entryPoint],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n }\n\n if (child) {\n child.on(\"error\", (error) => {\n console.error(\"Failed to start server:\", error);\n });\n\n child.on(\"exit\", (code, signal) => {\n if (!isRestarting && signal !== \"SIGTERM\" && signal !== \"SIGINT\") {\n console.info(`Server exited with code ${code}, restarting...`);\n startServer();\n }\n });\n }\n };\n\n startServer();\n\n const cleanup = () => {\n if (restartTimeout) clearTimeout(restartTimeout);\n\n if (child) {\n child.kill(\"SIGTERM\");\n\n setTimeout(() => {\n if (child && !child.killed) child.kill(\"SIGKILL\");\n }, 5000);\n }\n\n process.exit(0);\n };\n\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n process.on(\"uncaughtException\", (error) => {\n console.error(\"Uncaught Exception:\", error);\n cleanup();\n });\n } catch (error) {\n sheu.error(\"Development server failed to start:\");\n console.error(error);\n\n if (child) {\n (child as ChildProcess)?.kill?.();\n child = null;\n }\n\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the development server child process\n */\nexport function killDevelopmentServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}