arkos 2.0.0-next.13 → 2.0.0-next.16

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 (246) hide show
  1. package/README.md +144 -145
  2. package/cli.js +1 -0
  3. package/dist/cjs/app.js +7 -0
  4. package/dist/cjs/app.js.map +1 -1
  5. package/dist/cjs/exports/error-handler/index.js +15 -0
  6. package/dist/cjs/exports/error-handler/index.js.map +1 -1
  7. package/dist/cjs/modules/auth/auth.router.js +3 -0
  8. package/dist/cjs/modules/auth/auth.router.js.map +1 -1
  9. package/dist/cjs/modules/auth/auth.service.js +2 -0
  10. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  11. package/dist/cjs/modules/base/base.controller.js +15 -3
  12. package/dist/cjs/modules/base/base.controller.js.map +1 -1
  13. package/dist/cjs/modules/base/base.middlewares.js +19 -12
  14. package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
  15. package/dist/cjs/modules/base/base.service.js +5 -1
  16. package/dist/cjs/modules/base/base.service.js.map +1 -1
  17. package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js +9 -0
  18. package/dist/cjs/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
  19. package/dist/cjs/modules/error-handler/error-handler.controller.js +25 -42
  20. package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
  21. package/dist/cjs/modules/error-handler/utils/app-error.js +0 -1
  22. package/dist/cjs/modules/error-handler/utils/app-error.js.map +1 -1
  23. package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +8 -9
  24. package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
  25. package/dist/cjs/modules/error-handler/utils/errors.js +158 -0
  26. package/dist/cjs/modules/error-handler/utils/errors.js.map +1 -0
  27. package/dist/cjs/modules/error-handler/utils/multer-error-handler.js +39 -0
  28. package/dist/cjs/modules/error-handler/utils/multer-error-handler.js.map +1 -0
  29. package/dist/cjs/modules/file-upload/file-upload.controller.js +10 -14
  30. package/dist/cjs/modules/file-upload/file-upload.controller.js.map +1 -1
  31. package/dist/cjs/modules/file-upload/file-upload.router.js +2 -0
  32. package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -1
  33. package/dist/cjs/modules/swagger/swagger.router.js +8 -2
  34. package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
  35. package/dist/cjs/modules/swagger/utils/get-open-api-login-html.js +18 -0
  36. package/dist/cjs/modules/swagger/utils/get-open-api-login-html.js.map +1 -1
  37. package/dist/cjs/modules/swagger/utils/helpers/get-swagger-default-configs.js +5 -5
  38. package/dist/cjs/modules/swagger/utils/helpers/get-swagger-default-configs.js.map +1 -1
  39. package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js +1 -1
  40. package/dist/cjs/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
  41. package/dist/cjs/types/arkos-prisma-input.js.map +1 -1
  42. package/dist/cjs/types/index.js.map +1 -1
  43. package/dist/cjs/types/new-arkos-config.js.map +1 -1
  44. package/dist/cjs/types/router-config.js.map +1 -1
  45. package/dist/cjs/utils/arkos-router/arkos-router-openapi-manager.js +86 -28
  46. package/dist/cjs/utils/arkos-router/arkos-router-openapi-manager.js.map +1 -1
  47. package/dist/cjs/utils/arkos-router/index.js +11 -7
  48. package/dist/cjs/utils/arkos-router/index.js.map +1 -1
  49. package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
  50. package/dist/cjs/utils/arkos-router/types/upload-config.js.map +1 -1
  51. package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +34 -28
  52. package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -1
  53. package/dist/cjs/utils/arkos-router/utils/helpers/index.js +9 -6
  54. package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
  55. package/dist/cjs/utils/arkos-router/utils/helpers/upload-manager.js +334 -77
  56. package/dist/cjs/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
  57. package/dist/cjs/utils/bundler.js.map +1 -1
  58. package/dist/cjs/utils/cli/build.js +2 -3
  59. package/dist/cjs/utils/cli/build.js.map +1 -1
  60. package/dist/cjs/utils/cli/dev.js +11 -6
  61. package/dist/cjs/utils/cli/dev.js.map +1 -1
  62. package/dist/cjs/utils/cli/export-auth-action.js +5 -4
  63. package/dist/cjs/utils/cli/export-auth-action.js.map +1 -1
  64. package/dist/cjs/utils/cli/generate.js +6 -8
  65. package/dist/cjs/utils/cli/generate.js.map +1 -1
  66. package/dist/cjs/utils/cli/index.js +22 -19
  67. package/dist/cjs/utils/cli/index.js.map +1 -1
  68. package/dist/cjs/utils/cli/start.js +4 -2
  69. package/dist/cjs/utils/cli/start.js.map +1 -1
  70. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  71. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-controller-template.js +19 -7
  72. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-controller-template.js.map +1 -1
  73. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-multiple-components.js +7 -6
  74. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-multiple-components.js.map +1 -1
  75. package/dist/cjs/utils/cli/utils/template-generator/templates/policy-template.js +4 -4
  76. package/dist/cjs/utils/cli/utils/template-generator/templates/policy-template.js.map +1 -1
  77. package/dist/cjs/utils/cli/utils/template-generators.js +0 -6
  78. package/dist/cjs/utils/cli/utils/template-generators.js.map +1 -1
  79. package/dist/cjs/utils/define-config.js +5 -0
  80. package/dist/cjs/utils/define-config.js.map +1 -1
  81. package/dist/cjs/utils/dotenv.helpers.js +0 -6
  82. package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
  83. package/dist/cjs/utils/features/api.features.js +23 -5
  84. package/dist/cjs/utils/features/api.features.js.map +1 -1
  85. package/dist/cjs/utils/helpers/arkos-config.helpers.js +22 -2
  86. package/dist/cjs/utils/helpers/arkos-config.helpers.js.map +1 -1
  87. package/dist/cjs/utils/helpers/exit-error.js +1 -0
  88. package/dist/cjs/utils/helpers/exit-error.js.map +1 -1
  89. package/dist/cjs/utils/helpers/fs.helpers.js +25 -24
  90. package/dist/cjs/utils/helpers/fs.helpers.js.map +1 -1
  91. package/dist/cjs/utils/helpers/global.helpers.js +3 -2
  92. package/dist/cjs/utils/helpers/global.helpers.js.map +1 -1
  93. package/dist/cjs/utils/helpers/prisma.helpers.js +4 -5
  94. package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
  95. package/dist/cjs/utils/helpers/url-helpers.js +14 -0
  96. package/dist/cjs/utils/helpers/url-helpers.js.map +1 -0
  97. package/dist/cjs/utils/initialize-app.js +35 -6
  98. package/dist/cjs/utils/initialize-app.js.map +1 -1
  99. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +12 -6
  100. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  101. package/dist/cjs/utils/prisma/prisma-schema-parser.js +10 -3
  102. package/dist/cjs/utils/prisma/prisma-schema-parser.js.map +1 -1
  103. package/dist/cjs/utils/setup-app.js +58 -41
  104. package/dist/cjs/utils/setup-app.js.map +1 -1
  105. package/dist/esm/app.js +6 -0
  106. package/dist/esm/app.js.map +1 -1
  107. package/dist/esm/exports/error-handler/index.js +1 -0
  108. package/dist/esm/exports/error-handler/index.js.map +1 -1
  109. package/dist/esm/modules/auth/auth.router.js +3 -0
  110. package/dist/esm/modules/auth/auth.router.js.map +1 -1
  111. package/dist/esm/modules/auth/auth.service.js +2 -0
  112. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  113. package/dist/esm/modules/base/base.controller.js +15 -3
  114. package/dist/esm/modules/base/base.controller.js.map +1 -1
  115. package/dist/esm/modules/base/base.middlewares.js +19 -12
  116. package/dist/esm/modules/base/base.middlewares.js.map +1 -1
  117. package/dist/esm/modules/base/base.service.js +5 -1
  118. package/dist/esm/modules/base/base.service.js.map +1 -1
  119. package/dist/esm/modules/base/utils/helpers/base.service.helpers.js +9 -0
  120. package/dist/esm/modules/base/utils/helpers/base.service.helpers.js.map +1 -1
  121. package/dist/esm/modules/error-handler/error-handler.controller.js +22 -42
  122. package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
  123. package/dist/esm/modules/error-handler/utils/app-error.js +0 -1
  124. package/dist/esm/modules/error-handler/utils/app-error.js.map +1 -1
  125. package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +8 -9
  126. package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
  127. package/dist/esm/modules/error-handler/utils/errors.js +127 -0
  128. package/dist/esm/modules/error-handler/utils/errors.js.map +1 -0
  129. package/dist/esm/modules/error-handler/utils/multer-error-handler.js +34 -0
  130. package/dist/esm/modules/error-handler/utils/multer-error-handler.js.map +1 -0
  131. package/dist/esm/modules/file-upload/file-upload.controller.js +10 -14
  132. package/dist/esm/modules/file-upload/file-upload.controller.js.map +1 -1
  133. package/dist/esm/modules/file-upload/file-upload.router.js +2 -0
  134. package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
  135. package/dist/esm/modules/swagger/swagger.router.js +8 -2
  136. package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
  137. package/dist/esm/modules/swagger/utils/get-open-api-login-html.js +18 -0
  138. package/dist/esm/modules/swagger/utils/get-open-api-login-html.js.map +1 -1
  139. package/dist/esm/modules/swagger/utils/helpers/get-swagger-default-configs.js +5 -5
  140. package/dist/esm/modules/swagger/utils/helpers/get-swagger-default-configs.js.map +1 -1
  141. package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js +1 -1
  142. package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
  143. package/dist/esm/types/arkos-prisma-input.js.map +1 -1
  144. package/dist/esm/types/index.js.map +1 -1
  145. package/dist/esm/types/new-arkos-config.js.map +1 -1
  146. package/dist/esm/types/router-config.js.map +1 -1
  147. package/dist/esm/utils/arkos-router/arkos-router-openapi-manager.js +86 -28
  148. package/dist/esm/utils/arkos-router/arkos-router-openapi-manager.js.map +1 -1
  149. package/dist/esm/utils/arkos-router/index.js +11 -7
  150. package/dist/esm/utils/arkos-router/index.js.map +1 -1
  151. package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
  152. package/dist/esm/utils/arkos-router/types/upload-config.js.map +1 -1
  153. package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +34 -28
  154. package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -1
  155. package/dist/esm/utils/arkos-router/utils/helpers/index.js +9 -6
  156. package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
  157. package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js +334 -77
  158. package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
  159. package/dist/esm/utils/bundler.js.map +1 -1
  160. package/dist/esm/utils/cli/build.js +3 -4
  161. package/dist/esm/utils/cli/build.js.map +1 -1
  162. package/dist/esm/utils/cli/dev.js +12 -7
  163. package/dist/esm/utils/cli/dev.js.map +1 -1
  164. package/dist/esm/utils/cli/export-auth-action.js +5 -4
  165. package/dist/esm/utils/cli/export-auth-action.js.map +1 -1
  166. package/dist/esm/utils/cli/generate.js +6 -8
  167. package/dist/esm/utils/cli/generate.js.map +1 -1
  168. package/dist/esm/utils/cli/index.js +22 -19
  169. package/dist/esm/utils/cli/index.js.map +1 -1
  170. package/dist/esm/utils/cli/start.js +4 -2
  171. package/dist/esm/utils/cli/start.js.map +1 -1
  172. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  173. package/dist/esm/utils/cli/utils/template-generator/templates/generate-controller-template.js +16 -7
  174. package/dist/esm/utils/cli/utils/template-generator/templates/generate-controller-template.js.map +1 -1
  175. package/dist/esm/utils/cli/utils/template-generator/templates/generate-multiple-components.js +7 -6
  176. package/dist/esm/utils/cli/utils/template-generator/templates/generate-multiple-components.js.map +1 -1
  177. package/dist/esm/utils/cli/utils/template-generator/templates/policy-template.js +4 -4
  178. package/dist/esm/utils/cli/utils/template-generator/templates/policy-template.js.map +1 -1
  179. package/dist/esm/utils/cli/utils/template-generators.js +0 -6
  180. package/dist/esm/utils/cli/utils/template-generators.js.map +1 -1
  181. package/dist/esm/utils/define-config.js +5 -0
  182. package/dist/esm/utils/define-config.js.map +1 -1
  183. package/dist/esm/utils/dotenv.helpers.js +0 -6
  184. package/dist/esm/utils/dotenv.helpers.js.map +1 -1
  185. package/dist/esm/utils/features/api.features.js +23 -5
  186. package/dist/esm/utils/features/api.features.js.map +1 -1
  187. package/dist/esm/utils/helpers/arkos-config.helpers.js +20 -2
  188. package/dist/esm/utils/helpers/arkos-config.helpers.js.map +1 -1
  189. package/dist/esm/utils/helpers/exit-error.js +1 -0
  190. package/dist/esm/utils/helpers/exit-error.js.map +1 -1
  191. package/dist/esm/utils/helpers/fs.helpers.js +25 -24
  192. package/dist/esm/utils/helpers/fs.helpers.js.map +1 -1
  193. package/dist/esm/utils/helpers/global.helpers.js +1 -1
  194. package/dist/esm/utils/helpers/global.helpers.js.map +1 -1
  195. package/dist/esm/utils/helpers/prisma.helpers.js +4 -5
  196. package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
  197. package/dist/esm/utils/helpers/url-helpers.js +11 -0
  198. package/dist/esm/utils/helpers/url-helpers.js.map +1 -0
  199. package/dist/esm/utils/initialize-app.js +35 -6
  200. package/dist/esm/utils/initialize-app.js.map +1 -1
  201. package/dist/esm/utils/prisma/prisma-json-schema-generator.js +12 -6
  202. package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  203. package/dist/esm/utils/prisma/prisma-schema-parser.js +10 -3
  204. package/dist/esm/utils/prisma/prisma-schema-parser.js.map +1 -1
  205. package/dist/esm/utils/setup-app.js +59 -42
  206. package/dist/esm/utils/setup-app.js.map +1 -1
  207. package/dist/types/app.d.ts +5 -6
  208. package/dist/types/exports/error-handler/index.d.ts +1 -0
  209. package/dist/types/modules/auth/auth.service.d.ts +2 -6
  210. package/dist/types/modules/base/base.service.d.ts +2 -1
  211. package/dist/types/modules/error-handler/utils/app-error.d.ts +0 -2
  212. package/dist/types/modules/error-handler/utils/error-handler.helpers.d.ts +1 -1
  213. package/dist/types/modules/error-handler/utils/errors.d.ts +176 -0
  214. package/dist/types/modules/error-handler/utils/multer-error-handler.d.ts +7 -0
  215. package/dist/types/modules/file-upload/file-upload.controller.d.ts +0 -1
  216. package/dist/types/modules/swagger/utils/helpers/get-swagger-default-configs.d.ts +48 -2
  217. package/dist/types/types/arkos-prisma-input.d.ts +3 -2
  218. package/dist/types/types/index.d.ts +0 -21
  219. package/dist/types/types/new-arkos-config.d.ts +183 -14
  220. package/dist/types/types/router-config.d.ts +1 -1
  221. package/dist/types/utils/arkos-router/arkos-router-openapi-manager.d.ts +14 -1
  222. package/dist/types/utils/arkos-router/index.d.ts +76 -8
  223. package/dist/types/utils/arkos-router/types/index.d.ts +19 -6
  224. package/dist/types/utils/arkos-router/types/upload-config.d.ts +63 -7
  225. package/dist/types/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.d.ts +1 -1
  226. package/dist/types/utils/arkos-router/utils/helpers/index.d.ts +2 -0
  227. package/dist/types/utils/arkos-router/utils/helpers/upload-manager.d.ts +0 -36
  228. package/dist/types/utils/bundler.d.ts +1 -1
  229. package/dist/types/utils/cli/generate.d.ts +0 -1
  230. package/dist/types/utils/cli/start.d.ts +1 -1
  231. package/dist/types/utils/helpers/arkos-config.helpers.d.ts +2 -0
  232. package/dist/types/utils/helpers/fs.helpers.d.ts +1 -1
  233. package/dist/types/utils/helpers/global.helpers.d.ts +1 -0
  234. package/dist/types/utils/helpers/url-helpers.d.ts +1 -0
  235. package/dist/types/utils/prisma/prisma-schema-parser.d.ts +1 -0
  236. package/package.json +15 -15
  237. package/dist/cjs/utils/cli/utils/template-generator/templates/route-hook.template.js +0 -39
  238. package/dist/cjs/utils/cli/utils/template-generator/templates/route-hook.template.js.map +0 -1
  239. package/dist/cjs/utils/cli/utils/template-generator/templates/service-hook.template.js +0 -32
  240. package/dist/cjs/utils/cli/utils/template-generator/templates/service-hook.template.js.map +0 -1
  241. package/dist/esm/utils/cli/utils/template-generator/templates/route-hook.template.js +0 -36
  242. package/dist/esm/utils/cli/utils/template-generator/templates/route-hook.template.js.map +0 -1
  243. package/dist/esm/utils/cli/utils/template-generator/templates/service-hook.template.js +0 -29
  244. package/dist/esm/utils/cli/utils/template-generator/templates/service-hook.template.js.map +0 -1
  245. package/dist/types/utils/cli/utils/template-generator/templates/route-hook.template.d.ts +0 -2
  246. package/dist/types/utils/cli/utils/template-generator/templates/service-hook.template.d.ts +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAevE,qFAA2E;AAC3E,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;AAalD,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA2mBrD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,MAAM,KAAK,GAAG,IAAA,uBAAc,GAAE,EAAE,cAAc,EAAE,KAAK,EAAE,YAAY,CAAC;YAEpE,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;YACvD,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;gBACjB,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,aAAa,CACtC,KAAK,EAAE,OAAO,EACd,MAAM,CAAC,KAAK,EACZ,GAAG,CACJ,CAAC;gBACF,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;oBACpB,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,aAAa,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AM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AAh3BD,kCAg3BC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n AccessControlRules,\n DetailedAccessControlRule,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport {\n AuthenticateHookHandler,\n AuthenticateAfterHookHandler,\n AuthenticateErrorHookHandler,\n AuthorizeHookHandler,\n AuthorizeAfterHookHandler,\n AuthorizeErrorHookHandler,\n} from \"../../types/arkos-config/utils\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Runs a chain of `before` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to `onError` hooks.\n * - If a hook calls `skip()` — chain stops, core logic is bypassed, jumps to `after` hooks.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ skipped, error? }`\n */\n private async runHooks(\n hooks:\n | AuthenticateHookHandler\n | AuthenticateHookHandler[]\n | AuthorizeHookHandler\n | AuthorizeHookHandler[]\n | undefined,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ skipped: boolean; error?: unknown }> {\n if (!hooks) return { skipped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let skipCalled = false;\n\n try {\n await (hook as any)({\n req,\n skip: () => {\n skipCalled = true;\n },\n ...ctx,\n });\n } catch (err) {\n return { skipped: false, error: err };\n }\n\n if (skipCalled) return { skipped: true };\n }\n\n return { skipped: false };\n }\n\n /**\n * Runs a chain of `after` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to the global error handler.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ error? }`\n */\n private async runAfterHooks(\n hooks:\n | AuthenticateAfterHookHandler\n | AuthenticateAfterHookHandler[]\n | AuthorizeAfterHookHandler\n | AuthorizeAfterHookHandler[]\n | undefined,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ error?: unknown }> {\n if (!hooks) return {};\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n try {\n await (hook as any)({ req, ...ctx });\n } catch (err) {\n return { error: err };\n }\n }\n\n return {};\n }\n\n /**\n * Runs a chain of `onError` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to the global error handler.\n * - If a hook calls `skip()` — suppresses the error and jumps to `after` hooks.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ skipped, error? }`\n */\n private async runErrorHooks(\n hooks:\n | AuthenticateErrorHookHandler\n | AuthenticateErrorHookHandler[]\n | AuthorizeErrorHookHandler\n | AuthorizeErrorHookHandler[]\n | undefined,\n error: unknown,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ skipped: boolean; error?: unknown }> {\n if (!hooks) return { skipped: false, error };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let skipCalled = false;\n\n try {\n await (hook as any)({\n req,\n error,\n skip: () => {\n skipCalled = true;\n },\n ...ctx,\n });\n } catch (err) {\n return { skipped: false, error: err };\n }\n\n if (skipCalled) return { skipped: true };\n }\n\n return { skipped: false, error };\n }\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure: (() => {\n if (authConfigs?.jwt?.cookie?.secure !== undefined)\n return authConfigs?.jwt?.cookie?.secure;\n else if (process.env.JWT_COOKIE_SECURE !== undefined)\n return process.env.JWT_COOKIE_SECURE === \"true\";\n else return req.secure || req.headers[\"x-forwarded-proto\"] === \"https\";\n })(),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(new Date(user.passwordChangedAt).getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n private isWildcardAccess(config: AccessControlConfig): config is \"*\" {\n return config === \"*\";\n }\n\n private isRoleList(config: AccessControlConfig): config is string[] {\n return Array.isArray(config);\n }\n\n private isAccessRules(\n config: AccessControlConfig\n ): config is Partial<AccessControlRules> {\n return (\n typeof config === \"object\" && config !== null && !Array.isArray(config)\n );\n }\n\n private normalizeRuleToRoles(\n rule: string[] | DetailedAccessControlRule | \"*\" | undefined\n ): string[] {\n if (!rule) return [];\n if (rule === \"*\") return [\"*\"];\n if (Array.isArray(rule)) return rule;\n return rule.roles === \"*\" ? [\"*\"] : (rule.roles ?? []);\n }\n\n private resolveAuthorizedRoles(\n action: AccessAction,\n accessControl: AccessControlConfig\n ): string[] {\n if (this.isWildcardAccess(accessControl)) return [\"*\"];\n if (this.isRoleList(accessControl)) return accessControl;\n if (this.isAccessRules(accessControl))\n return this.normalizeRuleToRoles(accessControl[action]);\n return [];\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles = this.resolveAuthorizedRoles(action, accessControl);\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return (\n authorizedRoles?.[0] === \"*\" ||\n !!userRoles.some((role: string) => authorizedRoles.includes(role))\n );\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n *\n * @deprecated Will be removed on v2.0, use AuthService.authorize instead\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call AuthService.getAuthenticatedUser without setting up authentication\"\n );\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\") &&\n req?.headers?.authorization.split?.(\" \")?.[1]\n )\n token = req?.headers?.authorization.split(\" \")[1];\n\n if (\n !token &&\n req?.cookies?.arkos_access_token !== \"no-token\" &&\n req.cookies\n ) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) return null;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware to authenticate the request by extracting and verifying the JWT token and setting `req.user`.\n *\n * Runs `authentication.hooks.authenticate` before/after the authentication logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — extracts and verifies the JWT token, sets `req.user`.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if core logic throws — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * On custom routes, hooks defined in `arkosConfig` still apply since they are baked into this method.\n *\n * @example\n * ```ts\n * // custom route - hooks still run\n * router.get(\"/custom\", authService.authenticate, handler);\n * ```\n *\n * @example\n * ```ts\n * // skip built-in auth from a before hook\n * before: (ctx) => {\n * ctx.req.user = myCustomAuth(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authenticate;\n\n const before = await this.runHooks(hooks?.before, req);\n if (before.error) {\n const onError = await this.runErrorHooks(\n hooks?.onError,\n before.error,\n req\n );\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n\n if (!before.skipped) {\n try {\n if (isAuthenticationEnabled()) {\n const user = (await this.getAuthenticatedUser(req)) as User;\n if (!user) throw loginRequiredError;\n req.user = user;\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req);\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req);\n if (after.error) return next(after.error);\n\n next();\n }\n );\n\n /**\n * Middleware to authorize the authenticated user for a given action on a resource.\n *\n * Runs `authentication.hooks.authorize` before/after the authorization logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — checks user role/permissions against the access control rules.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if authorization fails — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * @param resource - The resource being accessed, in kebabCase (e.g. `\"product\"`, `\"cart-item\"`)\n * @param action - The action being performed (e.g. `\"View\"`, `\"Create\"`, `\"Delete\"`)\n * @param rule - Access control rules for this action. Accepts a role list, a wildcard, or a `DetailedAccessControlRule`.\n *\n * @example\n * ```ts\n * router.delete(\"/products/:id\",\n * authService.authenticate,\n * authService.authorize(\"product\", \"Delete\", [\"admin\"]),\n * handler\n * );\n * ```\n *\n * @example\n * ```ts\n * // skip built-in authorization from a before hook\n * before: (ctx) => {\n * ctx.req.user.role = myCustomRoleResolver(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks#authorize}\n * @since v1.6.0-beta\n */\n authorize(\n action: AccessAction,\n resource: string,\n rule?: string[] | DetailedAccessControlRule | \"*\"\n ): ArkosRequestHandler {\n authActionService.add(action, resource, { [action]: rule });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authorize;\n\n const before = await this.runHooks(hooks?.before, req, {\n action,\n resource,\n rule,\n });\n if (before.error) {\n const onError = await this.runErrorHooks(\n hooks?.onError,\n before.error,\n req,\n { action, resource, rule }\n );\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n\n if (!before.skipped) {\n try {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (!user.isSuperUser) {\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perform this action\",\n 403,\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n } else if (configs?.authentication?.mode === \"static\") {\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n { [action]: rule }\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n }\n }\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req, {\n action,\n resource,\n rule,\n });\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n if (after.error) return next(after.error);\n\n next();\n }\n );\n }\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n *\n * @deprecated Will be removed on v2.0, use AuthService.authenticate instead\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: User | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!isAuthenticationEnabled()) return false;\n if (!user) throw loginRequiredError;\n if (user?.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
1
+ {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAevE,qFAA2E;AAC3E,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;AAclD,MA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AAmC;QAGnC,MAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,KAAK,CAAC;QAEhC,IAAI,KAAK,EAAE,QAAQ,CAAC,0CAA0C,CAAC;YAC7D,MAAM,IAAI,KAAK,CACb,oFAAoF,CACrF,CAAC;QAEJ,6BAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,aAAa,CAAC,CAAC;QAEvD,OAAO,KAAK,EAAE,IAAsB,EAAoB,EAAE;YAExD,MAAM,OAAO,GAAG,IAAA,uBAAc,GAAE,CAAC;YAEjC,IAAI,CAAC,IAAA,4CAAqB,GAAE;gBAC1B,MAAM,KAAK,CACT,2FAA2F,CAC5F,CAAC;YAEJ,IAAI,CAAC,IAAA,8CAAuB,GAAE;gBAAE,OAAO,KAAK,CAAC;YAC7C,IAAI,CAAC,IAAI;gBAAE,MAAM,uCAAkB,CAAC;YACpC,IAAI,IAAI,EAAE,WAAW;gBAAE,OAAO,IAAI,CAAC;YAEnC,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;gBAChD,OAAO,MAAM,IAAI,CAAC,yBAAyB,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AAl3BD,kCAk3BC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n AccessControlRules,\n DetailedAccessControlRule,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport {\n AuthenticateHookHandler,\n AuthenticateAfterHookHandler,\n AuthenticateErrorHookHandler,\n AuthorizeHookHandler,\n AuthorizeAfterHookHandler,\n AuthorizeErrorHookHandler,\n} from \"../../types/arkos-config/utils\";\nimport { CookieOptions } from \"express\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Runs a chain of `before` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to `onError` hooks.\n * - If a hook calls `skip()` — chain stops, core logic is bypassed, jumps to `after` hooks.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ skipped, error? }`\n */\n private async runHooks(\n hooks:\n | AuthenticateHookHandler\n | AuthenticateHookHandler[]\n | AuthorizeHookHandler\n | AuthorizeHookHandler[]\n | undefined,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ skipped: boolean; error?: unknown }> {\n if (!hooks) return { skipped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let skipCalled = false;\n\n try {\n await (hook as any)({\n req,\n skip: () => {\n skipCalled = true;\n },\n ...ctx,\n });\n } catch (err) {\n return { skipped: false, error: err };\n }\n\n if (skipCalled) return { skipped: true };\n }\n\n return { skipped: false };\n }\n\n /**\n * Runs a chain of `after` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to the global error handler.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ error? }`\n */\n private async runAfterHooks(\n hooks:\n | AuthenticateAfterHookHandler\n | AuthenticateAfterHookHandler[]\n | AuthorizeAfterHookHandler\n | AuthorizeAfterHookHandler[]\n | undefined,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ error?: unknown }> {\n if (!hooks) return {};\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n try {\n await (hook as any)({ req, ...ctx });\n } catch (err) {\n return { error: err };\n }\n }\n\n return {};\n }\n\n /**\n * Runs a chain of `onError` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to the global error handler.\n * - If a hook calls `skip()` — suppresses the error and jumps to `after` hooks.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ skipped, error? }`\n */\n private async runErrorHooks(\n hooks:\n | AuthenticateErrorHookHandler\n | AuthenticateErrorHookHandler[]\n | AuthorizeErrorHookHandler\n | AuthorizeErrorHookHandler[]\n | undefined,\n error: unknown,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ skipped: boolean; error?: unknown }> {\n if (!hooks) return { skipped: false, error };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let skipCalled = false;\n\n try {\n await (hook as any)({\n req,\n error,\n skip: () => {\n skipCalled = true;\n },\n ...ctx,\n });\n } catch (err) {\n return { skipped: false, error: err };\n }\n\n if (skipCalled) return { skipped: true };\n }\n\n return { skipped: false, error };\n }\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure: (() => {\n if (authConfigs?.jwt?.cookie?.secure !== undefined)\n return authConfigs?.jwt?.cookie?.secure;\n else if (process.env.JWT_COOKIE_SECURE !== undefined)\n return process.env.JWT_COOKIE_SECURE === \"true\";\n else return req.secure || req.headers[\"x-forwarded-proto\"] === \"https\";\n })(),\n sameSite,\n domain: authConfigs?.jwt?.cookie?.domain || process.env.JWT_COOKIE_DOMAIN,\n ...arkosConfig?.authentication?.jwt?.cookie,\n } as CookieOptions;\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(new Date(user.passwordChangedAt).getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n private isWildcardAccess(config: AccessControlConfig): config is \"*\" {\n return config === \"*\";\n }\n\n private isRoleList(config: AccessControlConfig): config is string[] {\n return Array.isArray(config);\n }\n\n private isAccessRules(\n config: AccessControlConfig\n ): config is Partial<AccessControlRules> {\n return (\n typeof config === \"object\" && config !== null && !Array.isArray(config)\n );\n }\n\n private normalizeRuleToRoles(\n rule: string[] | DetailedAccessControlRule | \"*\" | undefined\n ): string[] {\n if (!rule) return [];\n if (rule === \"*\") return [\"*\"];\n if (Array.isArray(rule)) return rule;\n return rule.roles === \"*\" ? [\"*\"] : (rule.roles ?? []);\n }\n\n private resolveAuthorizedRoles(\n action: AccessAction,\n accessControl: AccessControlConfig\n ): string[] {\n if (this.isWildcardAccess(accessControl)) return [\"*\"];\n if (this.isRoleList(accessControl)) return accessControl;\n if (this.isAccessRules(accessControl))\n return this.normalizeRuleToRoles(accessControl[action]);\n return [];\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles = this.resolveAuthorizedRoles(action, accessControl);\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return (\n authorizedRoles?.[0] === \"*\" ||\n !!userRoles.some((role: string) => authorizedRoles.includes(role))\n );\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n *\n * @deprecated Will be removed on v2.0, use AuthService.authorize instead\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call AuthService.getAuthenticatedUser without setting up authentication\"\n );\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\") &&\n req?.headers?.authorization.split?.(\" \")?.[1]\n )\n token = req?.headers?.authorization.split(\" \")[1];\n\n if (\n !token &&\n req?.cookies?.arkos_access_token !== \"no-token\" &&\n req.cookies\n ) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) return null;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware to authenticate the request by extracting and verifying the JWT token and setting `req.user`.\n *\n * Runs `authentication.hooks.authenticate` before/after the authentication logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — extracts and verifies the JWT token, sets `req.user`.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if core logic throws — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * On custom routes, hooks defined in `arkosConfig` still apply since they are baked into this method.\n *\n * @example\n * ```ts\n * // custom route - hooks still run\n * router.get(\"/custom\", authService.authenticate, handler);\n * ```\n *\n * @example\n * ```ts\n * // skip built-in auth from a before hook\n * before: (ctx) => {\n * ctx.req.user = myCustomAuth(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authenticate;\n\n const before = await this.runHooks(hooks?.before, req);\n if (before.error) {\n const onError = await this.runErrorHooks(\n hooks?.onError,\n before.error,\n req\n );\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n\n if (!before.skipped) {\n try {\n if (isAuthenticationEnabled()) {\n const user = (await this.getAuthenticatedUser(req)) as User;\n if (!user) throw loginRequiredError;\n req.user = user;\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req);\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req);\n if (after.error) return next(after.error);\n\n next();\n }\n );\n\n /**\n * Middleware to authorize the authenticated user for a given action on a resource.\n *\n * Runs `authentication.hooks.authorize` before/after the authorization logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — checks user role/permissions against the access control rules.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if authorization fails — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * @param resource - The resource being accessed, in kebabCase (e.g. `\"product\"`, `\"cart-item\"`)\n * @param action - The action being performed (e.g. `\"View\"`, `\"Create\"`, `\"Delete\"`)\n * @param rule - Access control rules for this action. Accepts a role list, a wildcard, or a `DetailedAccessControlRule`.\n *\n * @example\n * ```ts\n * router.delete(\"/products/:id\",\n * authService.authenticate,\n * authService.authorize(\"product\", \"Delete\", [\"admin\"]),\n * handler\n * );\n * ```\n *\n * @example\n * ```ts\n * // skip built-in authorization from a before hook\n * before: (ctx) => {\n * ctx.req.user.role = myCustomRoleResolver(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks#authorize}\n * @since v1.6.0-beta\n */\n authorize(\n action: AccessAction,\n resource: string,\n rule?: string[] | DetailedAccessControlRule | \"*\"\n ): ArkosRequestHandler {\n authActionService.add(action, resource, { [action]: rule });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authorize;\n\n const before = await this.runHooks(hooks?.before, req, {\n action,\n resource,\n rule,\n });\n if (before.error) {\n const onError = await this.runErrorHooks(\n hooks?.onError,\n before.error,\n req,\n { action, resource, rule }\n );\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n\n if (!before.skipped) {\n try {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (!user.isSuperUser) {\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perform this action\",\n 403,\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n } else if (configs?.authentication?.mode === \"static\") {\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n { [action]: rule }\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n }\n }\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req, {\n action,\n resource,\n rule,\n });\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n if (after.error) return next(after.error);\n\n next();\n }\n );\n }\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n *\n * @deprecated Will be removed on v2.0, use AuthService.authenticate instead\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: User | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!isAuthenticationEnabled()) return false;\n if (!user) throw loginRequiredError;\n if (user?.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
@@ -66,8 +66,21 @@ class BaseController {
66
66
  accessToken: req?.accessToken,
67
67
  }),
68
68
  ]);
69
+ const take = serviceArgs[1]?.take ?? null;
70
+ const skip = serviceArgs[1]?.skip ?? 0;
71
+ const limit = take ?? total;
72
+ const currentPage = limit > 0 ? Math.floor(skip / limit) + 1 : 1;
73
+ const totalPages = limit > 0 ? Math.ceil(total / limit) : 1;
69
74
  data = records;
70
- additionalData = { total, results: records.length };
75
+ additionalData = {
76
+ total,
77
+ results: records.length,
78
+ page: currentPage,
79
+ pages: totalPages,
80
+ limit,
81
+ hasNextPage: currentPage < totalPages,
82
+ hasPrevPage: currentPage > 1,
83
+ };
71
84
  }
72
85
  const error = config.errorHandler
73
86
  ? config.errorHandler(data, req, this.modelName)
@@ -257,8 +270,7 @@ class BaseController {
257
270
  defaultResponseBuilder(data, additionalData, operationType) {
258
271
  if (operationType === "findMany" && additionalData)
259
272
  return {
260
- total: additionalData.total,
261
- results: additionalData.results,
273
+ ...additionalData,
262
274
  data,
263
275
  };
264
276
  if (operationType.includes("Many") &&
@@ -1 +1 @@
1
- {"version":3,"file":"base.controller.js","sourceRoot":"","sources":["../../../../src/modules/base/base.controller.ts"],"names":[],"mappings":";;;;;;AACA,qFAA4D;AAC5D,iDAA6C;AAC7C,iFAAwD;AACxD,iFAAgF;AAChF,0DAAkC;AAClC,+CAAkD;AAClD,4FAA6D;AAC7D,uGAAwE;AAExE,qEAA2E;AA4D3E,MAAa,cAAc;IAiBzB,YAAY,SAAsB;QAY1B,qBAAgB,GAAG,CAAC,MAAuB,EAAE,EAAE;YACrD,OAAO,IAAA,qBAAU,EACf,KAAK,EACH,GAAiB,EACjB,GAAkB,EAClB,IAAuB,EACvB,EAAE;gBACF,IAAI,MAAM,CAAC,KAAK,EAAE,WAAW;oBAAE,MAAM,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;gBAEnE,IAAI,MAAM,CAAC,oBAAoB,EAAE,CAAC;oBAChC,IACE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CACnC,CAAC,YAAY,EAAE,oBAAoB,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CACnD,EACD,CAAC;wBACD,OAAO,IAAI,CACT,IAAI,mBAAQ,CACV,yCAAyC,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,EACrF,GAAG,EACH,+BAA+B,CAChC,CACF,CAAC;oBACJ,CAAC;gBACH,CAAC;gBAED,IAAI,MAAM,CAAC,eAAe,IAAI,GAAG,CAAC,KAAK,CAAC,UAAU,KAAK,IAAI,EAAE,CAAC;oBAC5D,MAAM,IAAI,mBAAQ,CAChB,gDAAgD,MAAM,CAAC,aAAa,YAAY,EAChF,GAAG,CACJ,CAAC;gBACJ,CAAC;gBAED,IAAI,MAAM,CAAC,eAAe;oBAAE,GAAG,CAAC,KAAK,CAAC,UAAU,GAAG,KAAK,CAAC;gBAEz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gBAC3B,OAAO,EAAE,cAAc,CAAC,OAAO;gBAC/B,IAAI;aACL,CAAC;QAEJ,IACE,aAAa,CAAC,QAAQ,CAAC,MAAM,CAAC;YAC9B,IAAI;YACJ,OAAO,IAAI,KAAK,QAAQ;YACxB,OAAO,IAAI,IAAI;YAEf,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,EAAE,CAAC;QAEvC,IAAI,aAAa,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC;YACxD,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC;QAExC,OAAO,EAAE,IAAI,EAAE,CAAC;IAClB,CAAC;CA6HF;AA5cD,wCA4cC","sourcesContent":["import { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { BaseService } from \"./base.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { kebabCase, pascalCase } from \"../../utils/helpers/change-case.helpers\";\nimport pluralize from \"pluralize\";\nimport { APIFeatures } from \"../../exports/utils\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport loadableRegistry from \"../../components/arkos-loadable-registry\";\nimport { ArkosRouteHookInstance } from \"../../components/arkos-route-hook/types\";\nimport { routeHookReader } from \"../../components/arkos-route-hook/reader\";\nimport { PrismaModels } from \"../../generated\";\n\nexport interface OperationHooks {\n beforeQuery?: (req: ArkosRequest) => void | Promise<void>;\n afterQuery?: (\n queryData: { where: any; queryOptions: any },\n req: ArkosRequest\n ) => void | Promise<void>;\n beforeService?: (args: any[], req: ArkosRequest) => any[] | Promise<any[]>;\n afterService?: (data: any, req: ArkosRequest) => any | Promise<any>;\n beforeResponse?: (responseData: any, req: ArkosRequest) => any | Promise<any>;\n}\n\ninterface OperationConfig {\n operationType:\n | keyof Omit<ArkosRouteHookInstance<any>, \"__type\" | \"moduleName\">\n | \"batchUpdate\"\n | \"batchDelete\";\n serviceMethod: string;\n successStatus: number;\n queryFeatures: (\"filter\" | \"sort\" | \"limitFields\" | \"paginate\")[];\n requiresQueryForBulk?: boolean;\n preventORFilter?: boolean;\n responseBuilder?: (data: any, additionalData?: any) => any;\n errorHandler?: (\n data: any,\n req: ArkosRequest,\n modelName: string\n ) => AppError | null;\n usesRequestParams?: boolean;\n usesRequestBody?: boolean;\n hooks?: OperationHooks;\n}\n\n/**\n * The `BaseController` class provides standardized RESTful API endpoints\n * for any Prisma model based on its name. It supports automatic integration\n * with Prisma services and dynamic middleware hooks for extending behaviors.\n *\n * This controller includes:\n * - `createOne` / `createMany`\n * - `findOne` / `findMany`\n * - `updateOne` / `updateMany`\n * - `deleteOne` / `deleteMany`\n *\n * It handles:\n * - Prisma query options\n * - APIFeatures: filtering, sorting, pagination, field limiting\n * - Middleware hooks: `afterCreateOne`, `afterUpdateMany`, etc.\n *\n * @class BaseController\n *\n * @param {string} modelName - The Prisma model name this controller handles.\n *\n * @see {@link https://www.arkosjs.com/docs/reference/base-controller}\n *--\n * **See about how Arkos handles routers**\n * @see {@link https://www.arkosjs.com/docs/core-concepts/routing/setup}\n */\nexport class BaseController<TModuleName extends keyof PrismaModels<any>> {\n /**\n * Service instance to handle business logic operations\n * @public\n */\n service: BaseService<TModuleName>;\n\n /**\n * Name of the model this controller handles\n * @private\n */\n private modelName: string;\n\n /**\n * Creates a new BaseController instance\n * @param {string} modelName - The name of the model for which this controller will handle operations\n */\n constructor(modelName: TModuleName) {\n this.modelName = kebabCase(modelName);\n this.service = new BaseService(modelName);\n }\n\n private getRouteHook() {\n return loadableRegistry.getItem(\n \"ArkosRouteHook\",\n kebabCase(kebabCase(this.modelName))\n ) as ArkosRouteHookInstance<TModuleName>;\n }\n\n private executeOperation = (config: OperationConfig) => {\n return catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (config.hooks?.beforeQuery) await config.hooks.beforeQuery(req);\n\n if (config.requiresQueryForBulk) {\n if (\n Object.keys(req.query).every((key) =>\n [\"filterMode\", \"prismaQueryOptions\"].includes(key)\n )\n ) {\n return next(\n new AppError(\n `Filter criteria not provided for bulk ${config.operationType.replace(/Many$/, \"\")}.`,\n 400,\n \"MissingRequestQueryParameters\"\n )\n );\n }\n }\n\n if (config.preventORFilter && req.query.filterMode === \"OR\") {\n throw new AppError(\n `req.query.filterMode === OR is not valid for ${config.operationType} operation`,\n 400\n );\n }\n\n if (config.preventORFilter) req.query.filterMode = \"AND\";\n\n let apiFeatures = new APIFeatures(req, this.modelName);\n\n config.queryFeatures.forEach((feature) => {\n switch (feature) {\n case \"filter\":\n apiFeatures = apiFeatures.filter();\n break;\n case \"sort\":\n apiFeatures = apiFeatures.sort();\n break;\n case \"limitFields\":\n apiFeatures = apiFeatures.limitFields();\n break;\n case \"paginate\":\n apiFeatures = apiFeatures.paginate();\n break;\n }\n });\n\n const { where, ...queryOptions } = apiFeatures.filters;\n\n if (config.hooks?.afterQuery)\n await config.hooks.afterQuery({ where, queryOptions }, req);\n\n let serviceArgs = this.buildServiceArgs(\n config,\n req,\n where,\n queryOptions\n );\n\n if (config.hooks?.beforeService)\n serviceArgs = await config.hooks.beforeService(serviceArgs, req);\n\n const serviceMethod = this.service[\n config.serviceMethod as keyof BaseService<any>\n ] as Function;\n let result = await serviceMethod.apply(this.service, serviceArgs);\n\n if (config.hooks?.afterService)\n result = await config.hooks.afterService(result, req);\n\n let data = result;\n let additionalData: any = null;\n\n if (config.operationType === \"findMany\") {\n const [records, total] = await Promise.all([\n result,\n this.service.count(where, {\n user: req?.user,\n accessToken: req?.accessToken,\n }),\n ]);\n data = records;\n additionalData = { total, results: records.length };\n }\n\n const error = config.errorHandler\n ? config.errorHandler(data, req, this.modelName)\n : this.defaultErrorHandler(data, req, config.operationType);\n\n if (error) return next(error);\n\n let responseData = config.responseBuilder\n ? config.responseBuilder(data, additionalData)\n : this.defaultResponseBuilder(\n data,\n additionalData,\n config.operationType\n );\n\n if (config.hooks?.beforeResponse)\n responseData = await config.hooks.beforeResponse(responseData, req);\n\n const routeHook = this.getRouteHook();\n\n if (\n routeHook &&\n routeHookReader.getHooks(this.modelName, config.operationType as any)\n ?.after\n ) {\n this.setResponseData(req, res, responseData, config.successStatus);\n next();\n return;\n }\n\n if (config.operationType === \"deleteOne\") {\n res.status(config.successStatus).send();\n return;\n }\n\n res.status(config.successStatus).json(responseData);\n }\n );\n };\n\n /**\n * Sets response data for both legacy (req.responseData) and modern (res.locals) support\n */\n private setResponseData(\n req: ArkosRequest,\n res: ArkosResponse,\n data: any,\n status: number\n ): void {\n (res as any).originalData = data;\n req.responseData = data;\n res.locals.data = data;\n (res as any).originalStatus = status;\n req.responseStatus = status;\n res.locals.status = status;\n\n // Special handling for deleteOne\n if (status === 204) {\n req.additionalData = data;\n res.locals.additionalData = data;\n (res as any).originalAdditionalData = data;\n }\n }\n\n /**\n * Builds service method arguments based on operation configuration\n */\n private buildServiceArgs(\n config: OperationConfig,\n req: ArkosRequest,\n where: any,\n queryOptions: any\n ): any[] {\n const context = { user: req?.user, accessToken: req?.accessToken };\n const mergedOptions = deepmerge(req.prismaQueryOptions || {}, queryOptions);\n\n switch (config.operationType) {\n case \"createOne\":\n case \"createMany\":\n return [req.body, mergedOptions, context];\n\n case \"findMany\":\n return [where, queryOptions, context];\n\n case \"findOne\":\n return [{ ...req.params, ...where }, mergedOptions, context];\n\n case \"updateOne\":\n return [{ ...req.params, ...where }, req.body, mergedOptions, context];\n\n case \"updateMany\":\n // Remove include for bulk operations\n delete queryOptions.include;\n return [where, req.body, queryOptions, context];\n\n case \"batchUpdate\":\n return [req.body, mergedOptions, context];\n\n case \"deleteOne\":\n return [{ ...req.params, ...where }, context];\n\n case \"deleteMany\":\n return [where, context];\n\n case \"batchDelete\":\n return [req.body, context];\n\n default:\n throw new Error(`Unknown operation type: ${config.operationType}`);\n }\n }\n\n /**\n * Default error handler for operations\n */\n private defaultErrorHandler(\n data: any,\n req: ArkosRequest,\n operationType: string\n ): AppError | null {\n if (!data || (Array.isArray(data) && data.length === 0)) {\n // Handle different error scenarios\n if (operationType.includes(\"create\") || operationType.includes(\"batch\")) {\n return new AppError(\n \"Failed to create the resources. Please check your input.\",\n 400,\n { body: req.body }\n );\n }\n\n if (\n operationType === \"findOne\" ||\n operationType === \"updateOne\" ||\n operationType === \"deleteOne\"\n ) {\n if (\n Object.keys(req.params).length === 1 &&\n \"id\" in req.params &&\n req.params.id !== \"me\"\n ) {\n return new AppError(\n `${pascalCase(String(this.modelName))} with ID ${req.params?.id} not found`,\n 404,\n {},\n \"NotFound\"\n );\n } else {\n return new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"NotFound\"\n );\n }\n }\n\n if (operationType === \"updateMany\" || operationType === \"deleteMany\") {\n const isUpdate = operationType === \"updateMany\";\n return new AppError(\n isUpdate\n ? `${pluralize(pascalCase(String(this.modelName)))} not found`\n : `No records found to delete`,\n 404,\n {},\n \"NotFound\"\n );\n }\n }\n\n // Special handling for operations that return count\n if (\n data &&\n typeof data === \"object\" &&\n \"count\" in data &&\n data.count === 0\n ) {\n return new AppError(\n operationType === \"updateMany\"\n ? `${pluralize(pascalCase(String(this.modelName)))} not found`\n : `No records found to delete`,\n 404,\n {},\n \"NotFound\"\n );\n }\n\n return null;\n }\n\n /**\n * Default response builder for operations\n */\n private defaultResponseBuilder(\n data: any,\n additionalData: any,\n operationType: string\n ): any {\n if (operationType === \"findMany\" && additionalData)\n return {\n total: additionalData.total,\n results: additionalData.results,\n data,\n };\n\n if (\n operationType.includes(\"Many\") &&\n data &&\n typeof data === \"object\" &&\n \"count\" in data\n )\n return { results: data.count, data };\n\n if (operationType.includes(\"batch\") && Array.isArray(data))\n return { results: data.length, data };\n\n return { data };\n }\n\n /**\n * Creates a single resource\n */\n createOne = this.executeOperation({\n operationType: \"createOne\",\n serviceMethod: \"createOne\",\n successStatus: 201,\n queryFeatures: [\"limitFields\"],\n usesRequestBody: true,\n });\n\n /**\n * Creates multiple resources in a single operation\n */\n createMany = this.executeOperation({\n operationType: \"createMany\",\n serviceMethod: \"createMany\",\n successStatus: 201,\n queryFeatures: [\"limitFields\"],\n usesRequestBody: true,\n hooks: {\n async beforeQuery(req) {\n if (!req.body || (Array.isArray(req.body) && req.body.length === 0))\n throw new AppError(\n \"Expected request body array to contain at least on item but received none\",\n 400,\n { body: req.body },\n \"MissingArrayRequestBody\"\n );\n },\n },\n });\n\n /**\n * Retrieves multiple resources with filtering, sorting, pagination, and field selection\n */\n findMany = this.executeOperation({\n operationType: \"findMany\",\n serviceMethod: \"findMany\",\n successStatus: 200,\n queryFeatures: [\"filter\", \"sort\", \"limitFields\", \"paginate\"],\n });\n\n /**\n * Retrieves a single resource by its identifier\n */\n findOne = this.executeOperation({\n operationType: \"findOne\",\n serviceMethod: \"findOne\",\n successStatus: 200,\n queryFeatures: [\"limitFields\", \"filter\"],\n usesRequestParams: true,\n });\n\n /**\n * Updates a single resource by its identifier\n */\n updateOne = this.executeOperation({\n operationType: \"updateOne\",\n serviceMethod: \"updateOne\",\n successStatus: 200,\n queryFeatures: [\"limitFields\", \"filter\"],\n usesRequestParams: true,\n usesRequestBody: true,\n });\n\n /**\n * Updates multiple resources that match specified criteria\n */\n updateMany = this.executeOperation({\n operationType: \"updateMany\",\n serviceMethod: \"updateMany\",\n successStatus: 200,\n queryFeatures: [\"filter\", \"limitFields\"],\n requiresQueryForBulk: true,\n preventORFilter: true,\n usesRequestBody: true,\n });\n\n /**\n * Updates multiple resources with different data in a single transaction\n */\n batchUpdate = this.executeOperation({\n operationType: \"batchUpdate\",\n serviceMethod: \"batchUpdate\",\n successStatus: 200,\n queryFeatures: [\"limitFields\", \"filter\"],\n usesRequestBody: true,\n });\n\n /**\n * Deletes a single resource by its identifier\n */\n deleteOne = this.executeOperation({\n operationType: \"deleteOne\",\n serviceMethod: \"deleteOne\",\n successStatus: 204,\n queryFeatures: [\"filter\"],\n usesRequestParams: true,\n });\n\n /**\n * Deletes multiple resources that match specified criteria\n */\n deleteMany = this.executeOperation({\n operationType: \"deleteMany\",\n serviceMethod: \"deleteMany\",\n successStatus: 200,\n queryFeatures: [\"filter\"],\n requiresQueryForBulk: true,\n preventORFilter: true,\n });\n\n /**\n * Deletes multiple resources with different filters in a single transaction\n */\n batchDelete = this.executeOperation({\n operationType: \"batchDelete\",\n serviceMethod: \"batchDelete\",\n successStatus: 200,\n queryFeatures: [\"filter\"],\n usesRequestBody: true,\n });\n}\n"]}
1
+ {"version":3,"file":"base.controller.js","sourceRoot":"","sources":["../../../../src/modules/base/base.controller.ts"],"names":[],"mappings":";;;;;;AACA,qFAA4D;AAC5D,iDAA6C;AAC7C,iFAAwD;AACxD,iFAAgF;AAChF,0DAAkC;AAClC,+CAAkD;AAClD,4FAA6D;AAC7D,uGAAwE;AAExE,qEAA2E;AA4D3E,MAAa,cAAc;IAiBzB,YAAY,SAAsB;QAY1B,qBAAgB,GAAG,CAAC,MAAuB,EAAE,EAAE;YACrD,OAAO,IAAA,qBAAU,EACf,KAAK,EACH,GAAiB,EACjB,GAAkB,EAClB,IAAuB,EACvB,EAAE;gBACF,IAAI,MAAM,CAAC,KAAK,EAAE,WAAW;oBAAE,MAAM,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;gBAEnE,IAAI,MAAM,CAAC,oBAAoB,EAAE,CAAC;oBAChC,IACE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CACnC,CAAC,YAAY,EAAE,oBAAoB,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CACnD,EACD,CAAC;wBACD,OAAO,IAAI,CACT,IAAI,mBAAQ,CACV,yCAAyC,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,EACrF,GAAG,EACH,+BAA+B,CAChC,CACF,CAAC;oBACJ,CAAC;gBACH,CA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AAO,EAAE,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC;QAExC,OAAO,EAAE,IAAI,EAAE,CAAC;IAClB,CAAC;CA6HF;AA3dD,wCA2dC","sourcesContent":["import { ArkosRequest, ArkosResponse, ArkosNextFunction } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport { BaseService } from \"./base.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { kebabCase, pascalCase } from \"../../utils/helpers/change-case.helpers\";\nimport pluralize from \"pluralize\";\nimport { APIFeatures } from \"../../exports/utils\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport loadableRegistry from \"../../components/arkos-loadable-registry\";\nimport { ArkosRouteHookInstance } from \"../../components/arkos-route-hook/types\";\nimport { routeHookReader } from \"../../components/arkos-route-hook/reader\";\nimport { PrismaModels } from \"../../generated\";\n\nexport interface OperationHooks {\n beforeQuery?: (req: ArkosRequest) => void | Promise<void>;\n afterQuery?: (\n queryData: { where: any; queryOptions: any },\n req: ArkosRequest\n ) => void | Promise<void>;\n beforeService?: (args: any[], req: ArkosRequest) => any[] | Promise<any[]>;\n afterService?: (data: any, req: ArkosRequest) => any | Promise<any>;\n beforeResponse?: (responseData: any, req: ArkosRequest) => any | Promise<any>;\n}\n\ninterface OperationConfig {\n operationType:\n | keyof Omit<ArkosRouteHookInstance<any>, \"__type\" | \"moduleName\">\n | \"batchUpdate\"\n | \"batchDelete\";\n serviceMethod: string;\n successStatus: number;\n queryFeatures: (\"filter\" | \"sort\" | \"limitFields\" | \"paginate\")[];\n requiresQueryForBulk?: boolean;\n preventORFilter?: boolean;\n responseBuilder?: (data: any, additionalData?: any) => any;\n errorHandler?: (\n data: any,\n req: ArkosRequest,\n modelName: string\n ) => AppError | null;\n usesRequestParams?: boolean;\n usesRequestBody?: boolean;\n hooks?: OperationHooks;\n}\n\n/**\n * The `BaseController` class provides standardized RESTful API endpoints\n * for any Prisma model based on its name. It supports automatic integration\n * with Prisma services and dynamic middleware hooks for extending behaviors.\n *\n * This controller includes:\n * - `createOne` / `createMany`\n * - `findOne` / `findMany`\n * - `updateOne` / `updateMany`\n * - `deleteOne` / `deleteMany`\n *\n * It handles:\n * - Prisma query options\n * - APIFeatures: filtering, sorting, pagination, field limiting\n * - Middleware hooks: `afterCreateOne`, `afterUpdateMany`, etc.\n *\n * @class BaseController\n *\n * @param {string} modelName - The Prisma model name this controller handles.\n *\n * @see {@link https://www.arkosjs.com/docs/reference/base-controller}\n *--\n * **See about how Arkos handles routers**\n * @see {@link https://www.arkosjs.com/docs/core-concepts/routing/setup}\n */\nexport class BaseController<TModuleName extends keyof PrismaModels<any>> {\n /**\n * Service instance to handle business logic operations\n * @public\n */\n service: BaseService<TModuleName>;\n\n /**\n * Name of the model this controller handles\n * @private\n */\n private modelName: string;\n\n /**\n * Creates a new BaseController instance\n * @param {string} modelName - The name of the model for which this controller will handle operations\n */\n constructor(modelName: TModuleName) {\n this.modelName = kebabCase(modelName);\n this.service = new BaseService(modelName);\n }\n\n private getRouteHook() {\n return loadableRegistry.getItem(\n \"ArkosRouteHook\",\n kebabCase(kebabCase(this.modelName))\n ) as ArkosRouteHookInstance<TModuleName>;\n }\n\n private executeOperation = (config: OperationConfig) => {\n return catchAsync(\n async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (config.hooks?.beforeQuery) await config.hooks.beforeQuery(req);\n\n if (config.requiresQueryForBulk) {\n if (\n Object.keys(req.query).every((key) =>\n [\"filterMode\", \"prismaQueryOptions\"].includes(key)\n )\n ) {\n return next(\n new AppError(\n `Filter criteria not provided for bulk ${config.operationType.replace(/Many$/, \"\")}.`,\n 400,\n \"MissingRequestQueryParameters\"\n )\n );\n }\n }\n\n if (config.preventORFilter && req.query.filterMode === \"OR\") {\n throw new AppError(\n `req.query.filterMode === OR is not valid for ${config.operationType} operation`,\n 400\n );\n }\n\n if (config.preventORFilter) req.query.filterMode = \"AND\";\n\n let apiFeatures = new APIFeatures(req, this.modelName);\n\n config.queryFeatures.forEach((feature) => {\n switch (feature) {\n case \"filter\":\n apiFeatures = apiFeatures.filter();\n break;\n case \"sort\":\n apiFeatures = apiFeatures.sort();\n break;\n case \"limitFields\":\n apiFeatures = apiFeatures.limitFields();\n break;\n case \"paginate\":\n apiFeatures = apiFeatures.paginate();\n break;\n }\n });\n\n const { where, ...queryOptions } = apiFeatures.filters;\n\n if (config.hooks?.afterQuery)\n await config.hooks.afterQuery({ where, queryOptions }, req);\n\n let serviceArgs = this.buildServiceArgs(\n config,\n req,\n where,\n queryOptions\n );\n\n if (config.hooks?.beforeService)\n serviceArgs = await config.hooks.beforeService(serviceArgs, req);\n\n const serviceMethod = this.service[\n config.serviceMethod as keyof BaseService<any>\n ] as Function;\n let result = await serviceMethod.apply(this.service, serviceArgs);\n\n if (config.hooks?.afterService)\n result = await config.hooks.afterService(result, req);\n\n let data = result;\n let additionalData: any = null;\n\n if (config.operationType === \"findMany\") {\n const [records, total] = await Promise.all([\n result,\n this.service.count(where, {\n user: req?.user!,\n accessToken: req?.accessToken,\n }),\n ]);\n\n const take = serviceArgs[1]?.take ?? null;\n const skip = serviceArgs[1]?.skip ?? 0;\n\n const limit = take ?? total;\n const currentPage = limit > 0 ? Math.floor(skip / limit) + 1 : 1;\n const totalPages = limit > 0 ? Math.ceil(total / limit) : 1;\n\n data = records;\n additionalData = {\n total,\n results: records.length,\n page: currentPage,\n pages: totalPages,\n limit,\n hasNextPage: currentPage < totalPages,\n hasPrevPage: currentPage > 1,\n };\n }\n\n const error = config.errorHandler\n ? config.errorHandler(data, req, this.modelName)\n : this.defaultErrorHandler(data, req, config.operationType);\n\n if (error) return next(error);\n\n let responseData = config.responseBuilder\n ? config.responseBuilder(data, additionalData)\n : this.defaultResponseBuilder(\n data,\n additionalData,\n config.operationType\n );\n\n if (config.hooks?.beforeResponse)\n responseData = await config.hooks.beforeResponse(responseData, req);\n\n const routeHook = this.getRouteHook();\n\n if (\n routeHook &&\n routeHookReader.getHooks(this.modelName, config.operationType as any)\n ?.after\n ) {\n this.setResponseData(req, res, responseData, config.successStatus);\n next();\n return;\n }\n\n if (config.operationType === \"deleteOne\") {\n res.status(config.successStatus).send();\n return;\n }\n\n res.status(config.successStatus).json(responseData);\n }\n );\n };\n\n /**\n * Sets response data for both legacy (req.responseData) and modern (res.locals) support\n */\n private setResponseData(\n req: ArkosRequest,\n res: ArkosResponse,\n data: any,\n status: number\n ): void {\n (res as any).originalData = data;\n req.responseData = data;\n res.locals.data = data;\n (res as any).originalStatus = status;\n req.responseStatus = status;\n res.locals.status = status;\n\n // Special handling for deleteOne\n if (status === 204) {\n req.additionalData = data;\n res.locals.additionalData = data;\n (res as any).originalAdditionalData = data;\n }\n }\n\n /**\n * Builds service method arguments based on operation configuration\n */\n private buildServiceArgs(\n config: OperationConfig,\n req: ArkosRequest,\n where: any,\n queryOptions: any\n ): any[] {\n const context = { user: req?.user, accessToken: req?.accessToken };\n const mergedOptions = deepmerge(req.prismaQueryOptions || {}, queryOptions);\n\n switch (config.operationType) {\n case \"createOne\":\n case \"createMany\":\n return [req.body, mergedOptions, context];\n\n case \"findMany\":\n return [where, queryOptions, context];\n\n case \"findOne\":\n return [{ ...req.params, ...where }, mergedOptions, context];\n\n case \"updateOne\":\n return [{ ...req.params, ...where }, req.body, mergedOptions, context];\n\n case \"updateMany\":\n // Remove include for bulk operations\n delete queryOptions.include;\n return [where, req.body, queryOptions, context];\n\n case \"batchUpdate\":\n return [req.body, mergedOptions, context];\n\n case \"deleteOne\":\n return [{ ...req.params, ...where }, context];\n\n case \"deleteMany\":\n return [where, context];\n\n case \"batchDelete\":\n return [req.body, context];\n\n default:\n throw new Error(`Unknown operation type: ${config.operationType}`);\n }\n }\n\n /**\n * Default error handler for operations\n */\n private defaultErrorHandler(\n data: any,\n req: ArkosRequest,\n operationType: string\n ): AppError | null {\n if (!data || (Array.isArray(data) && data.length === 0)) {\n // Handle different error scenarios\n if (operationType.includes(\"create\") || operationType.includes(\"batch\")) {\n return new AppError(\n \"Failed to create the resources. Please check your input.\",\n 400,\n { body: req.body }\n );\n }\n\n if (\n operationType === \"findOne\" ||\n operationType === \"updateOne\" ||\n operationType === \"deleteOne\"\n ) {\n if (\n Object.keys(req.params).length === 1 &&\n \"id\" in req.params &&\n req.params.id !== \"me\"\n ) {\n return new AppError(\n `${pascalCase(String(this.modelName))} with ID ${req.params?.id} not found`,\n 404,\n {},\n \"NotFound\"\n );\n } else {\n return new AppError(\n `${pascalCase(String(this.modelName))} not found`,\n 404,\n {},\n \"NotFound\"\n );\n }\n }\n\n if (operationType === \"updateMany\" || operationType === \"deleteMany\") {\n const isUpdate = operationType === \"updateMany\";\n return new AppError(\n isUpdate\n ? `${pluralize(pascalCase(String(this.modelName)))} not found`\n : `No records found to delete`,\n 404,\n {},\n \"NotFound\"\n );\n }\n }\n\n // Special handling for operations that return count\n if (\n data &&\n typeof data === \"object\" &&\n \"count\" in data &&\n data.count === 0\n ) {\n return new AppError(\n operationType === \"updateMany\"\n ? `${pluralize(pascalCase(String(this.modelName)))} not found`\n : `No records found to delete`,\n 404,\n {},\n \"NotFound\"\n );\n }\n\n return null;\n }\n\n /**\n * Default response builder for operations\n */\n private defaultResponseBuilder(\n data: any,\n additionalData: any,\n operationType: string\n ): any {\n if (operationType === \"findMany\" && additionalData)\n return {\n ...additionalData,\n data,\n };\n\n if (\n operationType.includes(\"Many\") &&\n data &&\n typeof data === \"object\" &&\n \"count\" in data\n )\n return { results: data.count, data };\n\n if (operationType.includes(\"batch\") && Array.isArray(data))\n return { results: data.length, data };\n\n return { data };\n }\n\n /**\n * Creates a single resource\n */\n createOne = this.executeOperation({\n operationType: \"createOne\",\n serviceMethod: \"createOne\",\n successStatus: 201,\n queryFeatures: [\"limitFields\"],\n usesRequestBody: true,\n });\n\n /**\n * Creates multiple resources in a single operation\n */\n createMany = this.executeOperation({\n operationType: \"createMany\",\n serviceMethod: \"createMany\",\n successStatus: 201,\n queryFeatures: [\"limitFields\"],\n usesRequestBody: true,\n hooks: {\n async beforeQuery(req) {\n if (!req.body || (Array.isArray(req.body) && req.body.length === 0))\n throw new AppError(\n \"Expected request body array to contain at least on item but received none\",\n 400,\n { body: req.body },\n \"MissingArrayRequestBody\"\n );\n },\n },\n });\n\n /**\n * Retrieves multiple resources with filtering, sorting, pagination, and field selection\n */\n findMany = this.executeOperation({\n operationType: \"findMany\",\n serviceMethod: \"findMany\",\n successStatus: 200,\n queryFeatures: [\"filter\", \"sort\", \"limitFields\", \"paginate\"],\n });\n\n /**\n * Retrieves a single resource by its identifier\n */\n findOne = this.executeOperation({\n operationType: \"findOne\",\n serviceMethod: \"findOne\",\n successStatus: 200,\n queryFeatures: [\"limitFields\", \"filter\"],\n usesRequestParams: true,\n });\n\n /**\n * Updates a single resource by its identifier\n */\n updateOne = this.executeOperation({\n operationType: \"updateOne\",\n serviceMethod: \"updateOne\",\n successStatus: 200,\n queryFeatures: [\"limitFields\", \"filter\"],\n usesRequestParams: true,\n usesRequestBody: true,\n });\n\n /**\n * Updates multiple resources that match specified criteria\n */\n updateMany = this.executeOperation({\n operationType: \"updateMany\",\n serviceMethod: \"updateMany\",\n successStatus: 200,\n queryFeatures: [\"filter\", \"limitFields\"],\n requiresQueryForBulk: true,\n preventORFilter: true,\n usesRequestBody: true,\n });\n\n /**\n * Updates multiple resources with different data in a single transaction\n */\n batchUpdate = this.executeOperation({\n operationType: \"batchUpdate\",\n serviceMethod: \"batchUpdate\",\n successStatus: 200,\n queryFeatures: [\"limitFields\", \"filter\"],\n usesRequestBody: true,\n });\n\n /**\n * Deletes a single resource by its identifier\n */\n deleteOne = this.executeOperation({\n operationType: \"deleteOne\",\n serviceMethod: \"deleteOne\",\n successStatus: 204,\n queryFeatures: [\"filter\"],\n usesRequestParams: true,\n });\n\n /**\n * Deletes multiple resources that match specified criteria\n */\n deleteMany = this.executeOperation({\n operationType: \"deleteMany\",\n serviceMethod: \"deleteMany\",\n successStatus: 200,\n queryFeatures: [\"filter\"],\n requiresQueryForBulk: true,\n preventORFilter: true,\n });\n\n /**\n * Deletes multiple resources with different filters in a single transaction\n */\n batchDelete = this.executeOperation({\n operationType: \"batchDelete\",\n serviceMethod: \"batchDelete\",\n successStatus: 200,\n queryFeatures: [\"filter\"],\n usesRequestBody: true,\n });\n}\n"]}
@@ -18,6 +18,8 @@ const base_middlewares_helpers_1 = require("./utils/helpers/base.middlewares.hel
18
18
  const text_helpers_1 = require("../../utils/helpers/text.helpers.js");
19
19
  const dynamic_loader_1 = require("../../utils/dynamic-loader.js");
20
20
  const error_prettifier_1 = __importDefault(require("./utils/error-prettifier.js"));
21
+ const url_helpers_1 = require("../../utils/helpers/url-helpers.js");
22
+ const utils_1 = require("../../exports/utils/index.js");
21
23
  function callNext(_, _1, next) {
22
24
  next();
23
25
  }
@@ -128,12 +130,15 @@ function handleRequestLogs(req, res, next) {
128
130
  return "\x1b[0m";
129
131
  };
130
132
  res.on("finish", () => {
133
+ const isProduction = process.env.ARKOS_BUILD == "true";
131
134
  const duration = Date.now() - startTime;
132
135
  const now = new Date();
136
+ const date = now.toISOString().split("T")[0];
133
137
  const time = now.toTimeString().split(" ")[0];
138
+ const timestamp = isProduction ? `${date} ${time}` : time;
134
139
  const methodColor = methodColors[req.method] || "\x1b[0m";
135
140
  const statusColor = getStatusColor(res.statusCode);
136
- console.info(`[\x1b[36mInfo\x1b[0m] \x1b[90m${time}\x1b[0m ${methodColor}${req.method}\x1b[0m ${decodeURIComponent(req.originalUrl)} ${statusColor}${res.statusCode}\x1b[0m \x1b[35m${duration}ms\x1b[0m`);
141
+ console.info(`[\x1b[36mInfo\x1b[0m] \x1b[90m${timestamp}\x1b[0m ${methodColor}${req.method}\x1b[0m ${(0, url_helpers_1.lenientDecode)(req.originalUrl)} ${statusColor}${res.statusCode}\x1b[0m \x1b[35m${duration}ms\x1b[0m`);
137
142
  });
138
143
  next();
139
144
  }
@@ -184,21 +189,23 @@ function validateRequestInputs(routeConfig) {
184
189
  typeof openapi === "object" &&
185
190
  key != "body" &&
186
191
  openapi.parameters?.some((parameter) => parameter.in === validationToParameterMapping[key]) &&
187
- validators[key]) {
188
- throw Error(`Error in ${routeConfig.path}: when usign validation.${key} you must not define parameters under openapi.parameters as documentation of req.${key} because the ${validatorName} you passed under validation.${key} will be added as jsonSchema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`);
192
+ validators?.[key]) {
193
+ throw Error(`Error in ${routeConfig.path}: when usign validation.${key} you must not define parameters under openapi.parameters as documentation of req.${key} because the ${validatorName} you passed under validation.${key} will be added as jsonSchema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.
194
+
195
+ Read more about strict validation at https://www.arkosjs.com/docs/guides/validation/setup#strict-mode.
196
+ `);
189
197
  }
190
198
  if (openapi &&
191
199
  typeof openapi === "object" &&
192
200
  openapi.requestBody &&
193
- validators[key] &&
201
+ validators?.[key] &&
194
202
  key === "body") {
195
203
  throw Error(`When usign validation.${key} you must not define json-schema under openapi.requestBody as documentation for req.${key}, because the ${validatorName} you passed under validation.${key} will be added as json-schema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`);
196
204
  }
197
- if (strictValidation && !(key in validators))
198
- throw Error(`No { validation: { ${key}: ${validatorNameType} } } was found, while using strict validation you will need to pass undefined into ${key} in order to deny any request ${key} input.`);
199
- if (key in validators &&
205
+ if (key in (validators || {}) &&
200
206
  validators?.[key] !== undefined &&
201
207
  validators?.[key] !== false &&
208
+ validators?.[key] !== null &&
202
209
  !isValidValidator(validators[key]))
203
210
  throw Error(`Your validation resolver is set to ${arkosConfig.validation.resolver}, please provide a valid ${validatorName} in order to use in { validation: { ${key}: ${validatorNameType} } } under route ${routeConfig.path}`);
204
211
  });
@@ -207,12 +214,12 @@ function validateRequestInputs(routeConfig) {
207
214
  const reqInput = Object.keys(req[key] || {}).length > 0;
208
215
  const validator = validators?.[key];
209
216
  const notAllowedInputError = new error_handler_1.AppError(`Request ${key} is not allowed on this route`, 400, `Request${(0, text_helpers_1.capitalize)(key)}NotAllowed`, { [key]: req[key] });
210
- if (((typeof validators === "boolean" && validators === false) ||
211
- validator === false) &&
212
- reqInput)
217
+ if (validator === null && reqInput)
213
218
  throw notAllowedInputError;
214
- if (strictValidation && !validator && reqInput)
219
+ if (strictValidation && validator === undefined && reqInput)
215
220
  throw notAllowedInputError;
221
+ if (validator === false)
222
+ continue;
216
223
  if (validator)
217
224
  try {
218
225
  req[key] = await validatorFn(validator, req[key], arkosConfig.validation?.validationOptions);
@@ -222,7 +229,7 @@ function validateRequestInputs(routeConfig) {
222
229
  const isZod = validationConfig?.resolver === "zod";
223
230
  const prettifiedError = error_prettifier_1.default.prettify(resolver, err);
224
231
  const error = prettifiedError[0];
225
- throw new error_handler_1.AppError(error.message, 400, error.code, isZod ? err.format() : err);
232
+ throw new error_handler_1.AppError(error.message, 400, `InvalidRequest${(0, utils_1.pascalCase)(key)}`, isZod ? err.format() : err);
226
233
  }
227
234
  }
228
235
  next();
@@ -1 +1 @@
1
- {"version":3,"file":"base.middlewares.js","sourceRoot":"","sources":["../../../../src/modules/base/base.middlewares.ts"],"names":[],"mappings":";;;;;AAuBA,4BAEC;AA4BD,oCA4DC;AAkBD,wEAqBC;AAMD,8CA6CC;AAYD,oGA4BC;AAED,sDAuIC;AAnXD,yCAA8C;AAC9C,4FAA6D;AAC7D,+DAAmE;AACnE,4EAAmD;AACnD,kFAAyD;AAIzD,uFAAqF;AAErF,mEAA8D;AAC9D,+DAAkE;AAClE,gFAAuD;AAEvD,SAAgB,QAAQ,CAAC,CAAU,EAAE,EAAY,EAAE,IAAkB;IACnE,IAAI,EAAE,CAAC;AACT,CAAC;AAKD,SAAS,SAAS,CAAC,CAAM,EAAE,CAAM;IAC/B,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI;QAAE,OAAO,KAAK,CAAC;IACzC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC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,CAAC,UAAU,EAAE,iBAAiB,CAC1C,CAAC;gBACJ,CAAC;gBAAC,OAAO,GAAQ,EAAE,CAAC;oBAClB,MAAM,QAAQ,GAAG,gBAAgB,EAAE,QAAQ,CAAC;oBAC5C,MAAM,KAAK,GAAG,gBAAgB,EAAE,QAAQ,KAAK,KAAK,CAAC;oBAEnD,MAAM,eAAe,GAAG,0BAAe,CAAC,QAAQ,CAC9C,QAAe,EACf,GAAG,CACJ,CAAC;oBACF,MAAM,KAAK,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;oBACjC,MAAM,IAAI,wBAAQ,CAChB,KAAK,CAAC,OAAO,EACb,GAAG,EACH,KAAK,CAAC,IAAI,EACV,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,GAAG,CAC3B,CAAC;gBACJ,CAAC;QACL,CAAC;QAED,IAAI,EAAE,CAAC;IACT,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport {\n PrismaQueryOptions,\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n AuthPrismaQueryOptions,\n} from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AppError, catchAsync } from \"../../exports/error-handler\";\nimport validateDto from \"../../utils/validate-dto\";\nimport validateSchema from \"../../utils/validate-schema\";\nimport { ZodSchema } from \"zod\";\nimport { ClassConstructor } from \"class-transformer\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { resolvePrismaQueryOptions } from \"./utils/helpers/base.middlewares.helpers\";\nimport { ArkosRouteConfig } from \"../../utils/arkos-router/types\";\nimport { capitalize } from \"../../utils/helpers/text.helpers\";\nimport { isClass, isZodSchema } from \"../../utils/dynamic-loader\";\nimport errorPrettifier from \"./utils/error-prettifier\";\n\nexport function callNext(_: Request, _1: Response, next: NextFunction) {\n next();\n}\n\n/**\n * Deep comparison helper for objects\n */\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (typeof a !== \"object\" || typeof b !== \"object\") return a === b;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!keysB.includes(key)) return false;\n if (!deepEqual(a[key], b[key])) return false;\n }\n\n return true;\n}\n\n/**\n * Sends response with backward compatibility support\n * Compares current values against original values to detect middleware changes\n * If values were modified by subsequent middleware, use the modified version\n */\nexport function sendResponse(req: ArkosRequest, res: ArkosResponse) {\n let responseData;\n let responseStatus;\n\n const originalData = (res as any).originalData;\n const originalStatus = (res as any).originalStatus;\n\n const currentReqData = req.responseData;\n const currentReqStatus = req.responseStatus;\n const currentLocalsData = res.locals?.data;\n const currentLocalsStatus = res.locals?.status;\n\n if (\n currentReqData !== undefined &&\n !deepEqual(currentReqData, originalData)\n ) {\n responseData = currentReqData;\n } else if (\n currentLocalsData !== undefined &&\n !deepEqual(currentLocalsData, originalData)\n ) {\n responseData = currentLocalsData;\n } else if (originalData !== undefined) {\n responseData = originalData;\n } else {\n responseData = currentReqData ?? currentLocalsData;\n }\n\n if (currentReqStatus !== undefined && currentReqStatus !== originalStatus) {\n responseStatus = currentReqStatus;\n } else if (\n currentLocalsStatus !== undefined &&\n currentLocalsStatus !== originalStatus\n ) {\n responseStatus = currentLocalsStatus;\n } else if (originalStatus !== undefined) {\n responseStatus = originalStatus;\n } else {\n responseStatus = currentReqStatus ?? currentLocalsStatus;\n }\n\n // Send response\n\n if (Number(responseStatus) === 204) {\n res.status(Number(responseStatus)).send();\n } else if (\n (responseData !== undefined || responseData !== null) &&\n responseStatus\n ) {\n res.status(Number(responseStatus)).json(responseData);\n } else if (\n Number(responseStatus) &&\n (responseData === undefined || responseData === null)\n ) {\n res.status(Number(responseStatus)).send();\n } else {\n res.status(500).json({\n message: \"No status or data attached to the response\",\n });\n }\n}\n\n/**\n * Type representing all possible actions that can be performed on a controller\n * Combines both standard CRUD operations and auth-specific operations\n */\nexport type ControllerActions =\n | keyof PrismaQueryOptions<any>\n | keyof Omit<AuthPrismaQueryOptions<any>, keyof PrismaQueryOptions<any>>;\n\n/**\n * Middleware to add Prisma query options to the request's query parameters.\n *\n * @template T - The type of the Prisma model.\n * @param {PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>} prismaQueryOptions - The Prisma query options to attach.\n * @param {ControllerActions} action - The controller action to apply.\n * @returns A middleware function that attaches the query options to the request.\n */\nexport function addPrismaQueryOptionsToRequest<T extends Record<string, any>>(\n prismaQueryOptions: PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>,\n action: ControllerActions\n) {\n return (req: ArkosRequest, _: ArkosResponse, next: NextFunction) => {\n const configs = getArkosConfig();\n\n const resolvedOptions = resolvePrismaQueryOptions(\n prismaQueryOptions,\n action\n );\n\n const requestQueryOptions = configs?.request?.parameters\n ?.allowDangerousPrismaQueryOptions\n ? JSON.parse((req.query?.prismaQueryOptions as string) || \"{}\")\n : {};\n\n req.prismaQueryOptions = deepmerge(resolvedOptions, requestQueryOptions);\n\n next();\n };\n}\n\n/**\n * Logs request events with colored text such as errors, requests responses.\n *\n */\nexport function handleRequestLogs(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const startTime = Date.now();\n\n const methodColors = {\n GET: \"\\x1b[36m\", // Cyan\n POST: \"\\x1b[32m\", // Green\n PUT: \"\\x1b[33m\", // Orange/Yellow\n PATCH: \"\\x1b[33m\", // Orange/Yellow\n DELETE: \"\\x1b[31m\", // Red\n HEAD: \"\\x1b[34m\", // Blue\n OPTIONS: \"\\x1b[34m\", // Blue\n };\n\n const getStatusColor = (statusCode: number) => {\n if (statusCode >= 200 && statusCode < 300) return \"\\x1b[32m\";\n if (statusCode >= 300 && statusCode < 400) return \"\\x1b[33m\";\n if (statusCode >= 400 && statusCode < 500) return \"\\x1b[33m\";\n if (statusCode >= 500) return \"\\x1b[31m\";\n return \"\\x1b[0m\";\n };\n\n res.on(\"finish\", () => {\n const duration = Date.now() - startTime;\n\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n const methodColor =\n methodColors[req.method as keyof typeof methodColors] || \"\\x1b[0m\";\n const statusColor = getStatusColor(res.statusCode);\n\n console.info(\n `[\\x1b[36mInfo\\x1b[0m] \\x1b[90m${time}\\x1b[0m ${methodColor}${\n req.method\n }\\x1b[0m ${decodeURIComponent(req.originalUrl)} ${statusColor}${\n res.statusCode\n }\\x1b[0m \\x1b[35m${duration}ms\\x1b[0m`\n );\n });\n\n next();\n}\n\n/**\n * @deprecated Will be removed in v2.0, please ArkosRouter instead.\n */\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T>\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T> | ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n) {\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const validationConfigs = getArkosConfig()?.validation;\n let body = req.body;\n\n if (validationConfigs?.resolver === \"class-validator\" && schemaOrDtoClass)\n req.body = await validateDto(\n schemaOrDtoClass as ClassConstructor<T>,\n body,\n deepmerge(\n {\n whitelist: true,\n forbidNonWhitelisted: true,\n ...classValidatorValidationOptions,\n },\n validationConfigs?.validationOptions || {}\n )\n );\n else if (validationConfigs?.resolver === \"zod\" && schemaOrDtoClass)\n req.body = await validateSchema(schemaOrDtoClass as any, body);\n\n next();\n }\n );\n}\n\nexport function validateRequestInputs(routeConfig: ArkosRouteConfig) {\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const strictValidation = validationConfig?.strict;\n const validators = routeConfig?.validation;\n const openapi = routeConfig?.experimental?.openapi;\n\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (\n !validationConfig?.resolver &&\n Object.keys(routeConfig.validation || {}).length > 0\n )\n throw Error(\n `Trying to pass validators into route \\\"${routeConfig.path}\\\" config validation option without choosing a validation resolver under arkos config { validation: {} }.`\n );\n\n if ((validators as any) === true)\n throw Error(\n `Invalid value ${validators} passed to validation option, it can only receive false or object of { query, body, params }.`\n );\n\n const validatorFn: (validator: any, data: any, options: any) => Promise<any> =\n validationConfig?.resolver == \"zod\" ? validateSchema : validateDto;\n const validatorsKey: (\"body\" | \"query\" | \"params\")[] = [\n \"body\",\n \"query\",\n \"params\",\n ];\n\n const isValidValidator =\n validationConfig?.resolver == \"zod\" ? isZodSchema : isClass;\n const validatorName =\n validationConfig?.resolver == \"zod\" ? \"zod schema\" : \"class-validator dto\";\n const validatorNameType =\n validationConfig?.resolver == \"zod\" ? \"Schema\" : \"Dto\";\n\n if (typeof validators === \"object\")\n validatorsKey.forEach((key) => {\n if (\n openapi &&\n typeof openapi === \"object\" &&\n key != \"body\" &&\n openapi.parameters?.some(\n (parameter: any) => parameter.in === validationToParameterMapping[key]\n ) &&\n validators[key]\n ) {\n throw Error(\n `Error in ${routeConfig.path}: when usign validation.${key} you must not define parameters under openapi.parameters as documentation of req.${key} because the ${validatorName} you passed under validation.${key} will be added as jsonSchema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (\n openapi &&\n typeof openapi === \"object\" &&\n openapi.requestBody &&\n validators[key] &&\n key === \"body\"\n ) {\n throw Error(\n `When usign validation.${key} you must not define json-schema under openapi.requestBody as documentation for req.${key}, because the ${validatorName} you passed under validation.${key} will be added as json-schema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (strictValidation && !(key in validators))\n throw Error(\n `No { validation: { ${key}: ${validatorNameType} } } was found, while using strict validation you will need to pass undefined into ${key} in order to deny any request ${key} input.`\n );\n\n if (\n key in validators &&\n validators?.[key] !== undefined &&\n validators?.[key] !== false &&\n !isValidValidator(validators[key])\n )\n throw Error(\n `Your validation resolver is set to ${arkosConfig.validation!.resolver}, please provide a valid ${validatorName} in order to use in { validation: { ${key}: ${validatorNameType} } } under route ${routeConfig.path}`\n );\n });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n for (const key of validatorsKey) {\n const reqInput = Object.keys(req[key] || {}).length > 0;\n const validator = (validators as any)?.[key];\n const notAllowedInputError = new AppError(\n `Request ${key} is not allowed on this route`,\n 400,\n `Request${capitalize(key)}NotAllowed`,\n { [key]: req[key] }\n );\n\n if (\n ((typeof validators === \"boolean\" && validators === false) ||\n validator === false) &&\n reqInput\n )\n throw notAllowedInputError;\n\n if (strictValidation && !validator && reqInput)\n throw notAllowedInputError;\n if (validator)\n try {\n req[key] = await validatorFn(\n validator,\n req[key],\n arkosConfig.validation?.validationOptions\n );\n } catch (err: any) {\n const resolver = validationConfig?.resolver;\n const isZod = validationConfig?.resolver === \"zod\";\n\n const prettifiedError = errorPrettifier.prettify(\n resolver as any,\n err\n );\n const error = prettifiedError[0];\n throw new AppError(\n error.message,\n 400,\n error.code,\n isZod ? err.format() : err\n );\n }\n }\n\n next();\n }\n );\n}\n"]}
1
+ {"version":3,"file":"base.middlewares.js","sourceRoot":"","sources":["../../../../src/modules/base/base.middlewares.ts"],"names":[],"mappings":";;;;;AAyBA,4BAEC;AA4BD,oCA4DC;AAkBD,wEAqBC;AAMD,8CAkDC;AAYD,oGA4BC;AAED,sDAwIC;AA3XD,yCAA8C;AAC9C,4FAA6D;AAC7D,+DAAmE;AACnE,4EAAmD;AACnD,kFAAyD;AAIzD,uFAAqF;AAErF,mEAA8D;AAC9D,+DAAkE;AAClE,gFAAuD;AACvD,iEAAgE;AAChE,+CAAiD;AAEjD,SAAgB,QAAQ,CAAC,CAAU,EAAE,EAAY,EAAE,IAAkB;IACnE,IAAI,EAAE,CAAC;AACT,C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YAAY,EACrC,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,GAAG,CAAC,EAAE,CACpB,CAAC;YAGF,IAAI,SAAS,KAAK,IAAI,IAAI,QAAQ;gBAAE,MAAM,oBAAoB,CAAC;YAG/D,IAAI,gBAAgB,IAAI,SAAS,KAAK,SAAS,IAAI,QAAQ;gBACzD,MAAM,oBAAoB,CAAC;YAG7B,IAAI,SAAS,KAAK,KAAK;gBAAE,SAAS;YAGlC,IAAI,SAAS;gBACX,IAAI,CAAC;oBACH,GAAG,CAAC,GAAG,CAAC,GAAG,MAAM,WAAW,CAC1B,SAAS,EACT,GAAG,CAAC,GAAG,CAAC,EACR,WAAW,CAAC,UAAU,EAAE,iBAAiB,CAC1C,CAAC;gBACJ,CAAC;gBAAC,OAAO,GAAQ,EAAE,CAAC;oBAClB,MAAM,QAAQ,GAAG,gBAAgB,EAAE,QAAQ,CAAC;oBAC5C,MAAM,KAAK,GAAG,gBAAgB,EAAE,QAAQ,KAAK,KAAK,CAAC;oBAEnD,MAAM,eAAe,GAAG,0BAAe,CAAC,QAAQ,CAC9C,QAAe,EACf,GAAG,CACJ,CAAC;oBACF,MAAM,KAAK,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;oBACjC,MAAM,IAAI,wBAAQ,CAChB,KAAK,CAAC,OAAO,EACb,GAAG,EACH,iBAAiB,IAAA,kBAAU,EAAC,GAAG,CAAC,EAAE,EAClC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,GAAG,CAC3B,CAAC;gBACJ,CAAC;QACL,CAAC;QAED,IAAI,EAAE,CAAC;IACT,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport {\n PrismaQueryOptions,\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n AuthPrismaQueryOptions,\n} from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AppError, catchAsync } from \"../../exports/error-handler\";\nimport validateDto from \"../../utils/validate-dto\";\nimport validateSchema from \"../../utils/validate-schema\";\nimport { ZodSchema } from \"zod\";\nimport { ClassConstructor } from \"class-transformer\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { resolvePrismaQueryOptions } from \"./utils/helpers/base.middlewares.helpers\";\nimport { ArkosRouteConfig } from \"../../utils/arkos-router/types\";\nimport { capitalize } from \"../../utils/helpers/text.helpers\";\nimport { isClass, isZodSchema } from \"../../utils/dynamic-loader\";\nimport errorPrettifier from \"./utils/error-prettifier\";\nimport { lenientDecode } from \"../../utils/helpers/url-helpers\";\nimport { pascalCase } from \"../../exports/utils\";\n\nexport function callNext(_: Request, _1: Response, next: NextFunction) {\n next();\n}\n\n/**\n * Deep comparison helper for objects\n */\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (typeof a !== \"object\" || typeof b !== \"object\") return a === b;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!keysB.includes(key)) return false;\n if (!deepEqual(a[key], b[key])) return false;\n }\n\n return true;\n}\n\n/**\n * Sends response with backward compatibility support\n * Compares current values against original values to detect middleware changes\n * If values were modified by subsequent middleware, use the modified version\n */\nexport function sendResponse(req: ArkosRequest, res: ArkosResponse) {\n let responseData;\n let responseStatus;\n\n const originalData = (res as any).originalData;\n const originalStatus = (res as any).originalStatus;\n\n const currentReqData = req.responseData;\n const currentReqStatus = req.responseStatus;\n const currentLocalsData = res.locals?.data;\n const currentLocalsStatus = res.locals?.status;\n\n if (\n currentReqData !== undefined &&\n !deepEqual(currentReqData, originalData)\n ) {\n responseData = currentReqData;\n } else if (\n currentLocalsData !== undefined &&\n !deepEqual(currentLocalsData, originalData)\n ) {\n responseData = currentLocalsData;\n } else if (originalData !== undefined) {\n responseData = originalData;\n } else {\n responseData = currentReqData ?? currentLocalsData;\n }\n\n if (currentReqStatus !== undefined && currentReqStatus !== originalStatus) {\n responseStatus = currentReqStatus;\n } else if (\n currentLocalsStatus !== undefined &&\n currentLocalsStatus !== originalStatus\n ) {\n responseStatus = currentLocalsStatus;\n } else if (originalStatus !== undefined) {\n responseStatus = originalStatus;\n } else {\n responseStatus = currentReqStatus ?? currentLocalsStatus;\n }\n\n // Send response\n\n if (Number(responseStatus) === 204) {\n res.status(Number(responseStatus)).send();\n } else if (\n (responseData !== undefined || responseData !== null) &&\n responseStatus\n ) {\n res.status(Number(responseStatus)).json(responseData);\n } else if (\n Number(responseStatus) &&\n (responseData === undefined || responseData === null)\n ) {\n res.status(Number(responseStatus)).send();\n } else {\n res.status(500).json({\n message: \"No status or data attached to the response\",\n });\n }\n}\n\n/**\n * Type representing all possible actions that can be performed on a controller\n * Combines both standard CRUD operations and auth-specific operations\n */\nexport type ControllerActions =\n | keyof PrismaQueryOptions<any>\n | keyof Omit<AuthPrismaQueryOptions<any>, keyof PrismaQueryOptions<any>>;\n\n/**\n * Middleware to add Prisma query options to the request's query parameters.\n *\n * @template T - The type of the Prisma model.\n * @param {PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>} prismaQueryOptions - The Prisma query options to attach.\n * @param {ControllerActions} action - The controller action to apply.\n * @returns A middleware function that attaches the query options to the request.\n */\nexport function addPrismaQueryOptionsToRequest<T extends Record<string, any>>(\n prismaQueryOptions: PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>,\n action: ControllerActions\n) {\n return (req: ArkosRequest, _: ArkosResponse, next: NextFunction) => {\n const configs = getArkosConfig();\n\n const resolvedOptions = resolvePrismaQueryOptions(\n prismaQueryOptions,\n action\n );\n\n const requestQueryOptions = configs?.request?.parameters\n ?.allowDangerousPrismaQueryOptions\n ? JSON.parse((req.query?.prismaQueryOptions as string) || \"{}\")\n : {};\n\n req.prismaQueryOptions = deepmerge(resolvedOptions, requestQueryOptions);\n\n next();\n };\n}\n\n/**\n * Logs request events with colored text such as errors, requests responses.\n *\n */\nexport function handleRequestLogs(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const startTime = Date.now();\n\n const methodColors = {\n GET: \"\\x1b[36m\", // Cyan\n POST: \"\\x1b[32m\", // Green\n PUT: \"\\x1b[33m\", // Orange/Yellow\n PATCH: \"\\x1b[33m\", // Orange/Yellow\n DELETE: \"\\x1b[31m\", // Red\n HEAD: \"\\x1b[34m\", // Blue\n OPTIONS: \"\\x1b[34m\", // Blue\n };\n\n const getStatusColor = (statusCode: number) => {\n if (statusCode >= 200 && statusCode < 300) return \"\\x1b[32m\";\n if (statusCode >= 300 && statusCode < 400) return \"\\x1b[33m\";\n if (statusCode >= 400 && statusCode < 500) return \"\\x1b[33m\";\n if (statusCode >= 500) return \"\\x1b[31m\";\n return \"\\x1b[0m\";\n };\n\n res.on(\"finish\", () => {\n const isProduction = process.env.ARKOS_BUILD == \"true\";\n const duration = Date.now() - startTime;\n\n const now = new Date();\n\n const date = now.toISOString().split(\"T\")[0];\n const time = now.toTimeString().split(\" \")[0];\n\n const timestamp = isProduction ? `${date} ${time}` : time;\n\n const methodColor =\n methodColors[req.method as keyof typeof methodColors] || \"\\x1b[0m\";\n const statusColor = getStatusColor(res.statusCode);\n\n console.info(\n `[\\x1b[36mInfo\\x1b[0m] \\x1b[90m${timestamp}\\x1b[0m ${methodColor}${\n req.method\n }\\x1b[0m ${lenientDecode(req.originalUrl)} ${statusColor}${\n res.statusCode\n }\\x1b[0m \\x1b[35m${duration}ms\\x1b[0m`\n );\n });\n\n next();\n}\n\n/**\n * @deprecated Will be removed in v2.0, please ArkosRouter instead.\n */\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T>\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T> | ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n) {\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const validationConfigs = getArkosConfig()?.validation;\n let body = req.body;\n\n if (validationConfigs?.resolver === \"class-validator\" && schemaOrDtoClass)\n req.body = await validateDto(\n schemaOrDtoClass as ClassConstructor<T>,\n body,\n deepmerge(\n {\n whitelist: true,\n forbidNonWhitelisted: true,\n ...classValidatorValidationOptions,\n },\n validationConfigs?.validationOptions || {}\n )\n );\n else if (validationConfigs?.resolver === \"zod\" && schemaOrDtoClass)\n req.body = await validateSchema(schemaOrDtoClass as any, body);\n\n next();\n }\n );\n}\n\nexport function validateRequestInputs(routeConfig: ArkosRouteConfig) {\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const strictValidation = validationConfig?.strict;\n const validators = routeConfig?.validation;\n const openapi = routeConfig?.experimental?.openapi;\n\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (\n !validationConfig?.resolver &&\n Object.keys(routeConfig.validation || {}).length > 0\n )\n throw Error(\n `Trying to pass validators into route \\\"${routeConfig.path}\\\" config validation option without choosing a validation resolver under arkos config { validation: {} }.`\n );\n\n if ((validators as any) === true)\n throw Error(\n `Invalid value ${validators} passed to validation option, it can only receive false or object of { query, body, params }.`\n );\n\n const validatorFn: (validator: any, data: any, options: any) => Promise<any> =\n validationConfig?.resolver == \"zod\" ? validateSchema : validateDto;\n const validatorsKey: (\"body\" | \"query\" | \"params\")[] = [\n \"body\",\n \"query\",\n \"params\",\n ];\n\n const isValidValidator =\n validationConfig?.resolver == \"zod\" ? isZodSchema : isClass;\n const validatorName =\n validationConfig?.resolver == \"zod\" ? \"zod schema\" : \"class-validator dto\";\n const validatorNameType =\n validationConfig?.resolver == \"zod\" ? \"Schema\" : \"Dto\";\n\n if (typeof validators === \"object\")\n validatorsKey.forEach((key) => {\n if (\n openapi &&\n typeof openapi === \"object\" &&\n key != \"body\" &&\n openapi.parameters?.some(\n (parameter: any) => parameter.in === validationToParameterMapping[key]\n ) &&\n validators?.[key]\n ) {\n throw Error(\n `Error in ${routeConfig.path}: when usign validation.${key} you must not define parameters under openapi.parameters as documentation of req.${key} because the ${validatorName} you passed under validation.${key} will be added as jsonSchema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.\n\nRead more about strict validation at https://www.arkosjs.com/docs/guides/validation/setup#strict-mode.\n`\n );\n }\n\n if (\n openapi &&\n typeof openapi === \"object\" &&\n openapi.requestBody &&\n validators?.[key] &&\n key === \"body\"\n ) {\n throw Error(\n `When usign validation.${key} you must not define json-schema under openapi.requestBody as documentation for req.${key}, because the ${validatorName} you passed under validation.${key} will be added as json-schema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (\n key in (validators || {}) &&\n validators?.[key] !== undefined &&\n validators?.[key] !== false &&\n validators?.[key] !== null &&\n !isValidValidator(validators[key])\n )\n throw Error(\n `Your validation resolver is set to ${arkosConfig.validation!.resolver}, please provide a valid ${validatorName} in order to use in { validation: { ${key}: ${validatorNameType} } } under route ${routeConfig.path}`\n );\n });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n for (const key of validatorsKey) {\n const reqInput = Object.keys(req[key] || {}).length > 0;\n const validator = (validators as any)?.[key];\n const notAllowedInputError = new AppError(\n `Request ${key} is not allowed on this route`,\n 400,\n `Request${capitalize(key)}NotAllowed`,\n { [key]: req[key] }\n );\n\n // null explicitly set → always prohibit input\n if (validator === null && reqInput) throw notAllowedInputError;\n\n // strict mode + key not declared or set to undefined → prohibit input\n if (strictValidation && validator === undefined && reqInput)\n throw notAllowedInputError;\n\n // false explicitly set → allow input through without validation\n if (validator === false) continue;\n\n // a schema/dto was provided → validate\n if (validator)\n try {\n req[key] = await validatorFn(\n validator,\n req[key],\n arkosConfig.validation?.validationOptions\n );\n } catch (err: any) {\n const resolver = validationConfig?.resolver;\n const isZod = validationConfig?.resolver === \"zod\";\n\n const prettifiedError = errorPrettifier.prettify(\n resolver as any,\n err\n );\n const error = prettifiedError[0];\n throw new AppError(\n error.message,\n 400,\n `InvalidRequest${pascalCase(key)}`,\n isZod ? err.format() : err\n );\n }\n }\n\n next();\n }\n );\n}\n"]}
@@ -86,7 +86,11 @@ class BaseService {
86
86
  [],
87
87
  list: modelFields?.filter((field) => field.isRelation && field.isArray) || [],
88
88
  };
89
- this.prisma = (0, prisma_helpers_1.getPrismaInstance)();
89
+ }
90
+ get prisma() {
91
+ if (!this.prismaInstace)
92
+ this.prismaInstace = (0, prisma_helpers_1.getPrismaInstance)();
93
+ return this.prismaInstace;
90
94
  }
91
95
  getServiceHook() {
92
96
  return arkos_loadable_registry_1.default.getItem("ArkosServiceHook", (0, change_case_helpers_1.kebabCase)(this.modelName));