@intlayer/backend 7.2.1-canary.0 → 7.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (290) hide show
  1. package/dist/esm/utils/AI/aiSdk.mjs +7 -1
  2. package/dist/esm/utils/AI/aiSdk.mjs.map +1 -1
  3. package/dist/types/controllers/dictionary.controller.d.ts.map +1 -1
  4. package/dist/types/controllers/projectAccessKey.controller.d.ts.map +1 -1
  5. package/dist/types/controllers/tag.controller.d.ts.map +1 -1
  6. package/dist/types/emails/InviteUserEmail.d.ts +4 -4
  7. package/dist/types/emails/InviteUserEmail.d.ts.map +1 -1
  8. package/dist/types/emails/MagicLinkEmail.d.ts +4 -4
  9. package/dist/types/emails/OAuthTokenCreatedEmail.d.ts +4 -4
  10. package/dist/types/emails/PasswordChangeConfirmation.d.ts +4 -4
  11. package/dist/types/emails/PasswordChangeConfirmation.d.ts.map +1 -1
  12. package/dist/types/emails/ResetUserPassword.d.ts +4 -4
  13. package/dist/types/emails/ResetUserPassword.d.ts.map +1 -1
  14. package/dist/types/emails/SubscriptionPaymentCancellation.d.ts +4 -4
  15. package/dist/types/emails/SubscriptionPaymentError.d.ts +4 -4
  16. package/dist/types/emails/SubscriptionPaymentSuccess.d.ts +4 -4
  17. package/dist/types/emails/SubscriptionPaymentSuccess.d.ts.map +1 -1
  18. package/dist/types/emails/ValidateUserEmail.d.ts +4 -4
  19. package/dist/types/emails/Welcome.d.ts +4 -4
  20. package/dist/types/models/dictionary.model.d.ts +4 -4
  21. package/dist/types/models/dictionary.model.d.ts.map +1 -1
  22. package/dist/types/models/discussion.model.d.ts +2 -2
  23. package/dist/types/models/discussion.model.d.ts.map +1 -1
  24. package/dist/types/models/oAuth2.model.d.ts +3 -3
  25. package/dist/types/models/oAuth2.model.d.ts.map +1 -1
  26. package/dist/types/routes/ai.routes.d.ts.map +1 -1
  27. package/dist/types/routes/project.routes.d.ts.map +1 -1
  28. package/dist/types/schemas/dictionary.schema.d.ts +6 -6
  29. package/dist/types/schemas/dictionary.schema.d.ts.map +1 -1
  30. package/dist/types/schemas/discussion.schema.d.ts +6 -6
  31. package/dist/types/schemas/oAuth2.schema.d.ts +5 -5
  32. package/dist/types/schemas/organization.schema.d.ts +6 -6
  33. package/dist/types/schemas/plans.schema.d.ts +6 -6
  34. package/dist/types/schemas/project.schema.d.ts +6 -6
  35. package/dist/types/schemas/project.schema.d.ts.map +1 -1
  36. package/dist/types/schemas/session.schema.d.ts +6 -6
  37. package/dist/types/schemas/tag.schema.d.ts +6 -6
  38. package/dist/types/schemas/user.schema.d.ts +6 -6
  39. package/dist/types/services/email.service.d.ts +11 -11
  40. package/dist/types/utils/filtersAndPagination/getDictionaryFiltersAndPagination.d.ts +2 -2
  41. package/dist/types/utils/filtersAndPagination/getDiscussionFiltersAndPagination.d.ts +2 -2
  42. package/dist/types/utils/filtersAndPagination/getOrganizationFiltersAndPagination.d.ts +2 -2
  43. package/dist/types/utils/filtersAndPagination/getProjectFiltersAndPagination.d.ts +2 -2
  44. package/dist/types/utils/filtersAndPagination/getTagFiltersAndPagination.d.ts +2 -2
  45. package/package.json +17 -18
  46. package/dist/cjs/_virtual/_utils_asset.cjs +0 -98
  47. package/dist/cjs/_virtual/rolldown_runtime.cjs +0 -25
  48. package/dist/cjs/controllers/ai.controller.cjs +0 -381
  49. package/dist/cjs/controllers/ai.controller.cjs.map +0 -1
  50. package/dist/cjs/controllers/dictionary.controller.cjs +0 -463
  51. package/dist/cjs/controllers/dictionary.controller.cjs.map +0 -1
  52. package/dist/cjs/controllers/eventListener.controller.cjs +0 -53
  53. package/dist/cjs/controllers/eventListener.controller.cjs.map +0 -1
  54. package/dist/cjs/controllers/newsletter.controller.cjs +0 -164
  55. package/dist/cjs/controllers/newsletter.controller.cjs.map +0 -1
  56. package/dist/cjs/controllers/oAuth2.controller.cjs +0 -22
  57. package/dist/cjs/controllers/oAuth2.controller.cjs.map +0 -1
  58. package/dist/cjs/controllers/organization.controller.cjs +0 -492
  59. package/dist/cjs/controllers/organization.controller.cjs.map +0 -1
  60. package/dist/cjs/controllers/project.controller.cjs +0 -430
  61. package/dist/cjs/controllers/project.controller.cjs.map +0 -1
  62. package/dist/cjs/controllers/projectAccessKey.controller.cjs +0 -161
  63. package/dist/cjs/controllers/projectAccessKey.controller.cjs.map +0 -1
  64. package/dist/cjs/controllers/search.controller.cjs +0 -14
  65. package/dist/cjs/controllers/search.controller.cjs.map +0 -1
  66. package/dist/cjs/controllers/stripe.controller.cjs +0 -149
  67. package/dist/cjs/controllers/stripe.controller.cjs.map +0 -1
  68. package/dist/cjs/controllers/tag.controller.cjs +0 -226
  69. package/dist/cjs/controllers/tag.controller.cjs.map +0 -1
  70. package/dist/cjs/controllers/user.controller.cjs +0 -269
  71. package/dist/cjs/controllers/user.controller.cjs.map +0 -1
  72. package/dist/cjs/emails/InviteUserEmail.cjs +0 -325
  73. package/dist/cjs/emails/InviteUserEmail.cjs.map +0 -1
  74. package/dist/cjs/emails/MagicLinkEmail.cjs +0 -242
  75. package/dist/cjs/emails/MagicLinkEmail.cjs.map +0 -1
  76. package/dist/cjs/emails/OAuthTokenCreatedEmail.cjs +0 -301
  77. package/dist/cjs/emails/OAuthTokenCreatedEmail.cjs.map +0 -1
  78. package/dist/cjs/emails/PasswordChangeConfirmation.cjs +0 -177
  79. package/dist/cjs/emails/PasswordChangeConfirmation.cjs.map +0 -1
  80. package/dist/cjs/emails/ResetUserPassword.cjs +0 -240
  81. package/dist/cjs/emails/ResetUserPassword.cjs.map +0 -1
  82. package/dist/cjs/emails/SubscriptionPaymentCancellation.cjs +0 -202
  83. package/dist/cjs/emails/SubscriptionPaymentCancellation.cjs.map +0 -1
  84. package/dist/cjs/emails/SubscriptionPaymentError.cjs +0 -202
  85. package/dist/cjs/emails/SubscriptionPaymentError.cjs.map +0 -1
  86. package/dist/cjs/emails/SubscriptionPaymentSuccess.cjs +0 -208
  87. package/dist/cjs/emails/SubscriptionPaymentSuccess.cjs.map +0 -1
  88. package/dist/cjs/emails/ValidateUserEmail.cjs +0 -240
  89. package/dist/cjs/emails/ValidateUserEmail.cjs.map +0 -1
  90. package/dist/cjs/emails/Welcome.cjs +0 -216
  91. package/dist/cjs/emails/Welcome.cjs.map +0 -1
  92. package/dist/cjs/emails/index.cjs +0 -25
  93. package/dist/cjs/export.cjs +0 -24
  94. package/dist/cjs/index.cjs +0 -91
  95. package/dist/cjs/index.cjs.map +0 -1
  96. package/dist/cjs/logger/index.cjs +0 -13
  97. package/dist/cjs/logger/index.cjs.map +0 -1
  98. package/dist/cjs/middlewares/oAuth2.middleware.cjs +0 -42
  99. package/dist/cjs/middlewares/oAuth2.middleware.cjs.map +0 -1
  100. package/dist/cjs/middlewares/request.middleware.cjs +0 -17
  101. package/dist/cjs/middlewares/request.middleware.cjs.map +0 -1
  102. package/dist/cjs/middlewares/sessionAuth.middleware.cjs +0 -22
  103. package/dist/cjs/middlewares/sessionAuth.middleware.cjs.map +0 -1
  104. package/dist/cjs/models/dictionary.model.cjs +0 -10
  105. package/dist/cjs/models/dictionary.model.cjs.map +0 -1
  106. package/dist/cjs/models/discussion.model.cjs +0 -10
  107. package/dist/cjs/models/discussion.model.cjs.map +0 -1
  108. package/dist/cjs/models/oAuth2.model.cjs +0 -10
  109. package/dist/cjs/models/oAuth2.model.cjs.map +0 -1
  110. package/dist/cjs/models/organization.model.cjs +0 -10
  111. package/dist/cjs/models/organization.model.cjs.map +0 -1
  112. package/dist/cjs/models/project.model.cjs +0 -10
  113. package/dist/cjs/models/project.model.cjs.map +0 -1
  114. package/dist/cjs/models/session.model.cjs +0 -10
  115. package/dist/cjs/models/session.model.cjs.map +0 -1
  116. package/dist/cjs/models/tag.model.cjs +0 -10
  117. package/dist/cjs/models/tag.model.cjs.map +0 -1
  118. package/dist/cjs/models/user.model.cjs +0 -10
  119. package/dist/cjs/models/user.model.cjs.map +0 -1
  120. package/dist/cjs/routes/ai.routes.cjs +0 -75
  121. package/dist/cjs/routes/ai.routes.cjs.map +0 -1
  122. package/dist/cjs/routes/dictionary.routes.cjs +0 -64
  123. package/dist/cjs/routes/dictionary.routes.cjs.map +0 -1
  124. package/dist/cjs/routes/eventListener.routes.cjs +0 -20
  125. package/dist/cjs/routes/eventListener.routes.cjs.map +0 -1
  126. package/dist/cjs/routes/newsletter.routes.cjs +0 -34
  127. package/dist/cjs/routes/newsletter.routes.cjs.map +0 -1
  128. package/dist/cjs/routes/organization.routes.cjs +0 -70
  129. package/dist/cjs/routes/organization.routes.cjs.map +0 -1
  130. package/dist/cjs/routes/project.routes.cjs +0 -83
  131. package/dist/cjs/routes/project.routes.cjs.map +0 -1
  132. package/dist/cjs/routes/search.routes.cjs +0 -20
  133. package/dist/cjs/routes/search.routes.cjs.map +0 -1
  134. package/dist/cjs/routes/stripe.routes.cjs +0 -34
  135. package/dist/cjs/routes/stripe.routes.cjs.map +0 -1
  136. package/dist/cjs/routes/tags.routes.cjs +0 -40
  137. package/dist/cjs/routes/tags.routes.cjs.map +0 -1
  138. package/dist/cjs/routes/user.routes.cjs +0 -58
  139. package/dist/cjs/routes/user.routes.cjs.map +0 -1
  140. package/dist/cjs/schemas/dictionary.schema.cjs +0 -73
  141. package/dist/cjs/schemas/dictionary.schema.cjs.map +0 -1
  142. package/dist/cjs/schemas/discussion.schema.cjs +0 -81
  143. package/dist/cjs/schemas/discussion.schema.cjs.map +0 -1
  144. package/dist/cjs/schemas/oAuth2.schema.cjs +0 -49
  145. package/dist/cjs/schemas/oAuth2.schema.cjs.map +0 -1
  146. package/dist/cjs/schemas/organization.schema.cjs +0 -62
  147. package/dist/cjs/schemas/organization.schema.cjs.map +0 -1
  148. package/dist/cjs/schemas/plans.schema.cjs +0 -75
  149. package/dist/cjs/schemas/plans.schema.cjs.map +0 -1
  150. package/dist/cjs/schemas/project.schema.cjs +0 -112
  151. package/dist/cjs/schemas/project.schema.cjs.map +0 -1
  152. package/dist/cjs/schemas/session.schema.cjs +0 -43
  153. package/dist/cjs/schemas/session.schema.cjs.map +0 -1
  154. package/dist/cjs/schemas/tag.schema.cjs +0 -62
  155. package/dist/cjs/schemas/tag.schema.cjs.map +0 -1
  156. package/dist/cjs/schemas/user.schema.cjs +0 -87
  157. package/dist/cjs/schemas/user.schema.cjs.map +0 -1
  158. package/dist/cjs/services/dictionary.service.cjs +0 -176
  159. package/dist/cjs/services/dictionary.service.cjs.map +0 -1
  160. package/dist/cjs/services/email.service.cjs +0 -155
  161. package/dist/cjs/services/email.service.cjs.map +0 -1
  162. package/dist/cjs/services/oAuth2.service.cjs +0 -211
  163. package/dist/cjs/services/oAuth2.service.cjs.map +0 -1
  164. package/dist/cjs/services/organization.service.cjs +0 -106
  165. package/dist/cjs/services/organization.service.cjs.map +0 -1
  166. package/dist/cjs/services/project.service.cjs +0 -89
  167. package/dist/cjs/services/project.service.cjs.map +0 -1
  168. package/dist/cjs/services/projectAccessKey.service.cjs +0 -111
  169. package/dist/cjs/services/projectAccessKey.service.cjs.map +0 -1
  170. package/dist/cjs/services/subscription.service.cjs +0 -184
  171. package/dist/cjs/services/subscription.service.cjs.map +0 -1
  172. package/dist/cjs/services/tag.service.cjs +0 -88
  173. package/dist/cjs/services/tag.service.cjs.map +0 -1
  174. package/dist/cjs/services/user.service.cjs +0 -120
  175. package/dist/cjs/services/user.service.cjs.map +0 -1
  176. package/dist/cjs/types/Routes.cjs +0 -0
  177. package/dist/cjs/types/dictionary.types.cjs +0 -0
  178. package/dist/cjs/types/discussion.types.cjs +0 -0
  179. package/dist/cjs/types/oAuth2.types.cjs +0 -0
  180. package/dist/cjs/types/organization.types.cjs +0 -0
  181. package/dist/cjs/types/plan.types.cjs +0 -0
  182. package/dist/cjs/types/project.types.cjs +0 -0
  183. package/dist/cjs/types/session.types.cjs +0 -0
  184. package/dist/cjs/types/tag.types.cjs +0 -0
  185. package/dist/cjs/types/user.types.cjs +0 -10
  186. package/dist/cjs/types/user.types.cjs.map +0 -1
  187. package/dist/cjs/utils/AI/aiSdk.cjs +0 -94
  188. package/dist/cjs/utils/AI/aiSdk.cjs.map +0 -1
  189. package/dist/cjs/utils/AI/askDocQuestion/askDocQuestion.cjs +0 -201
  190. package/dist/cjs/utils/AI/askDocQuestion/askDocQuestion.cjs.map +0 -1
  191. package/dist/cjs/utils/AI/askDocQuestion/indexMarkdownFiles.cjs +0 -150
  192. package/dist/cjs/utils/AI/askDocQuestion/indexMarkdownFiles.cjs.map +0 -1
  193. package/dist/cjs/utils/AI/auditDictionary/index.cjs +0 -60
  194. package/dist/cjs/utils/AI/auditDictionary/index.cjs.map +0 -1
  195. package/dist/cjs/utils/AI/auditDictionaryField/index.cjs +0 -63
  196. package/dist/cjs/utils/AI/auditDictionaryField/index.cjs.map +0 -1
  197. package/dist/cjs/utils/AI/auditDictionaryMetadata/index.cjs +0 -45
  198. package/dist/cjs/utils/AI/auditDictionaryMetadata/index.cjs.map +0 -1
  199. package/dist/cjs/utils/AI/auditTag/index.cjs +0 -40
  200. package/dist/cjs/utils/AI/auditTag/index.cjs.map +0 -1
  201. package/dist/cjs/utils/AI/autocomplete/index.cjs +0 -41
  202. package/dist/cjs/utils/AI/autocomplete/index.cjs.map +0 -1
  203. package/dist/cjs/utils/AI/customQuery/index.cjs +0 -27
  204. package/dist/cjs/utils/AI/customQuery/index.cjs.map +0 -1
  205. package/dist/cjs/utils/AI/translateJSON/index.cjs +0 -71
  206. package/dist/cjs/utils/AI/translateJSON/index.cjs.map +0 -1
  207. package/dist/cjs/utils/access.cjs +0 -0
  208. package/dist/cjs/utils/accessControl.cjs +0 -133
  209. package/dist/cjs/utils/accessControl.cjs.map +0 -1
  210. package/dist/cjs/utils/auth/getAuth.cjs +0 -218
  211. package/dist/cjs/utils/auth/getAuth.cjs.map +0 -1
  212. package/dist/cjs/utils/cors.cjs +0 -33
  213. package/dist/cjs/utils/cors.cjs.map +0 -1
  214. package/dist/cjs/utils/ensureArrayQueryFilter.cjs +0 -13
  215. package/dist/cjs/utils/ensureArrayQueryFilter.cjs.map +0 -1
  216. package/dist/cjs/utils/ensureMongoDocumentToObject.cjs +0 -16
  217. package/dist/cjs/utils/ensureMongoDocumentToObject.cjs.map +0 -1
  218. package/dist/cjs/utils/errors/ErrorHandler.cjs +0 -76
  219. package/dist/cjs/utils/errors/ErrorHandler.cjs.map +0 -1
  220. package/dist/cjs/utils/errors/ErrorsClass.cjs +0 -54
  221. package/dist/cjs/utils/errors/ErrorsClass.cjs.map +0 -1
  222. package/dist/cjs/utils/errors/errorCodes.cjs +0 -1387
  223. package/dist/cjs/utils/errors/errorCodes.cjs.map +0 -1
  224. package/dist/cjs/utils/errors/index.cjs +0 -8
  225. package/dist/cjs/utils/extractJSON.cjs +0 -61
  226. package/dist/cjs/utils/extractJSON.cjs.map +0 -1
  227. package/dist/cjs/utils/filtersAndPagination/getDictionaryFiltersAndPagination.cjs +0 -94
  228. package/dist/cjs/utils/filtersAndPagination/getDictionaryFiltersAndPagination.cjs.map +0 -1
  229. package/dist/cjs/utils/filtersAndPagination/getDiscussionFiltersAndPagination.cjs +0 -65
  230. package/dist/cjs/utils/filtersAndPagination/getDiscussionFiltersAndPagination.cjs.map +0 -1
  231. package/dist/cjs/utils/filtersAndPagination/getFiltersAndPaginationFromBody.cjs +0 -36
  232. package/dist/cjs/utils/filtersAndPagination/getFiltersAndPaginationFromBody.cjs.map +0 -1
  233. package/dist/cjs/utils/filtersAndPagination/getOrganizationFiltersAndPagination.cjs +0 -49
  234. package/dist/cjs/utils/filtersAndPagination/getOrganizationFiltersAndPagination.cjs.map +0 -1
  235. package/dist/cjs/utils/filtersAndPagination/getProjectFiltersAndPagination.cjs +0 -53
  236. package/dist/cjs/utils/filtersAndPagination/getProjectFiltersAndPagination.cjs.map +0 -1
  237. package/dist/cjs/utils/filtersAndPagination/getTagFiltersAndPagination.cjs +0 -57
  238. package/dist/cjs/utils/filtersAndPagination/getTagFiltersAndPagination.cjs.map +0 -1
  239. package/dist/cjs/utils/filtersAndPagination/getUserFiltersAndPagination.cjs +0 -74
  240. package/dist/cjs/utils/filtersAndPagination/getUserFiltersAndPagination.cjs.map +0 -1
  241. package/dist/cjs/utils/httpStatusCodes.cjs +0 -401
  242. package/dist/cjs/utils/httpStatusCodes.cjs.map +0 -1
  243. package/dist/cjs/utils/mapper/dictionary.cjs +0 -29
  244. package/dist/cjs/utils/mapper/dictionary.cjs.map +0 -1
  245. package/dist/cjs/utils/mapper/organization.cjs +0 -19
  246. package/dist/cjs/utils/mapper/organization.cjs.map +0 -1
  247. package/dist/cjs/utils/mapper/project.cjs +0 -26
  248. package/dist/cjs/utils/mapper/project.cjs.map +0 -1
  249. package/dist/cjs/utils/mapper/session.cjs +0 -15
  250. package/dist/cjs/utils/mapper/session.cjs.map +0 -1
  251. package/dist/cjs/utils/mapper/tag.cjs +0 -25
  252. package/dist/cjs/utils/mapper/tag.cjs.map +0 -1
  253. package/dist/cjs/utils/mapper/user.cjs +0 -24
  254. package/dist/cjs/utils/mapper/user.cjs.map +0 -1
  255. package/dist/cjs/utils/mergeFunctionTypes.cjs +0 -0
  256. package/dist/cjs/utils/mongoDB/connectDB.cjs +0 -32
  257. package/dist/cjs/utils/mongoDB/connectDB.cjs.map +0 -1
  258. package/dist/cjs/utils/mongoDB/types.cjs +0 -0
  259. package/dist/cjs/utils/oAuth2.cjs +0 -25
  260. package/dist/cjs/utils/oAuth2.cjs.map +0 -1
  261. package/dist/cjs/utils/permissions.cjs +0 -103
  262. package/dist/cjs/utils/permissions.cjs.map +0 -1
  263. package/dist/cjs/utils/plan.cjs +0 -63
  264. package/dist/cjs/utils/plan.cjs.map +0 -1
  265. package/dist/cjs/utils/rateLimiter.cjs +0 -48
  266. package/dist/cjs/utils/rateLimiter.cjs.map +0 -1
  267. package/dist/cjs/utils/removeObjectKeys.cjs +0 -11
  268. package/dist/cjs/utils/removeObjectKeys.cjs.map +0 -1
  269. package/dist/cjs/utils/responseData.cjs +0 -33
  270. package/dist/cjs/utils/responseData.cjs.map +0 -1
  271. package/dist/cjs/utils/validation/validateArray.cjs +0 -31
  272. package/dist/cjs/utils/validation/validateArray.cjs.map +0 -1
  273. package/dist/cjs/utils/validation/validateDictionary.cjs +0 -35
  274. package/dist/cjs/utils/validation/validateDictionary.cjs.map +0 -1
  275. package/dist/cjs/utils/validation/validateEmail.cjs +0 -20
  276. package/dist/cjs/utils/validation/validateEmail.cjs.map +0 -1
  277. package/dist/cjs/utils/validation/validateOrganization.cjs +0 -43
  278. package/dist/cjs/utils/validation/validateOrganization.cjs.map +0 -1
  279. package/dist/cjs/utils/validation/validatePhone.cjs +0 -20
  280. package/dist/cjs/utils/validation/validatePhone.cjs.map +0 -1
  281. package/dist/cjs/utils/validation/validateProject.cjs +0 -55
  282. package/dist/cjs/utils/validation/validateProject.cjs.map +0 -1
  283. package/dist/cjs/utils/validation/validateString.cjs +0 -21
  284. package/dist/cjs/utils/validation/validateString.cjs.map +0 -1
  285. package/dist/cjs/utils/validation/validateTag.cjs +0 -47
  286. package/dist/cjs/utils/validation/validateTag.cjs.map +0 -1
  287. package/dist/cjs/utils/validation/validateUser.cjs +0 -47
  288. package/dist/cjs/utils/validation/validateUser.cjs.map +0 -1
  289. package/dist/cjs/webhooks/stripe.webhook.cjs +0 -116
  290. package/dist/cjs/webhooks/stripe.webhook.cjs.map +0 -1
@@ -1,184 +0,0 @@
1
- const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
2
- const require_logger_index = require('../logger/index.cjs');
3
- const require_utils_errors_ErrorsClass = require('../utils/errors/ErrorsClass.cjs');
4
- const require_services_organization_service = require('./organization.service.cjs');
5
- const require_services_user_service = require('./user.service.cjs');
6
- const require_services_email_service = require('./email.service.cjs');
7
- const require_utils_plan = require('../utils/plan.cjs');
8
- let stripe = require("stripe");
9
- stripe = require_rolldown_runtime.__toESM(stripe);
10
-
11
- //#region src/services/subscription.service.ts
12
- const addOrUpdateSubscription = async (subscriptionId, priceId, customerId, userId, organization, status) => {
13
- const stripe$1 = new stripe.default(process.env.STRIPE_SECRET_KEY);
14
- const user = await require_services_user_service.getUserById(userId);
15
- if (!user) throw new require_utils_errors_ErrorsClass.GenericError("USER_NOT_FOUND", { userId });
16
- if (String(user.customerId) !== customerId) {
17
- user.customerId = customerId;
18
- await user.save();
19
- }
20
- const planInfo = require_utils_plan.retrievePlanInformation(priceId);
21
- const subscriptions = await stripe$1.subscriptions.list({
22
- customer: customerId,
23
- status: "active",
24
- limit: 1
25
- });
26
- if (subscriptions.data.length >= 1) {
27
- const otherSubscriptionArray = subscriptions.data.filter((subscription) => subscription.id !== subscriptionId);
28
- for (const subscription of otherSubscriptionArray) await stripe$1.subscriptions.cancel(subscription.id);
29
- }
30
- const updatedOrganization = await require_services_organization_service.updatePlan(organization, {
31
- creatorId: user.id,
32
- priceId,
33
- customerId,
34
- subscriptionId,
35
- type: planInfo.type,
36
- period: planInfo.period,
37
- status
38
- });
39
- if (!updatedOrganization) throw new require_utils_errors_ErrorsClass.GenericError("ORGANIZATION_UPDATE_FAILED", { organizationId: organization.id });
40
- require_logger_index.logger.info(`Plan updated for organization ${organization.id} - ${planInfo.type} - ${planInfo.period}`);
41
- return updatedOrganization.plan ?? null;
42
- };
43
- const cancelSubscription = async (subscriptionId, organizationId) => {
44
- const organization = await require_services_organization_service.getOrganizationById(organizationId);
45
- if (!organization) throw new require_utils_errors_ErrorsClass.GenericError("ORGANIZATION_NOT_FOUND", { subscriptionId });
46
- if (!subscriptionId) throw new require_utils_errors_ErrorsClass.GenericError("NO_SUBSCRIPTION_ID_PROVIDED");
47
- if (!organization.plan) throw new require_utils_errors_ErrorsClass.GenericError("ORGANIZATION_PLAN_NOT_FOUND", {
48
- subscriptionId,
49
- organizationId: organization.id
50
- });
51
- const updatedOrganization = await require_services_organization_service.updatePlan(organization, { status: "canceled" });
52
- if (!updatedOrganization) throw new require_utils_errors_ErrorsClass.GenericError("ORGANIZATION_UPDATE_FAILED", { organizationId: organization.id });
53
- require_logger_index.logger.info(`Cancelled plan for organization ${updatedOrganization.id} - ${updatedOrganization.plan?.type} - ${updatedOrganization.plan?.period}`);
54
- return updatedOrganization.plan ?? null;
55
- };
56
- const changeSubscriptionStatus = async (subscriptionId, status, userId, organizationId) => {
57
- const organization = await require_services_organization_service.getOrganizationById(organizationId);
58
- if (!organization) throw new require_utils_errors_ErrorsClass.GenericError("ORGANIZATION_NOT_FOUND", {
59
- userId,
60
- subscriptionId
61
- });
62
- if (!organization.plan) throw new require_utils_errors_ErrorsClass.GenericError("ORGANIZATION_PLAN_NOT_FOUND", {
63
- userId,
64
- subscriptionId,
65
- organizationId: organization.id
66
- });
67
- const updatedOrganization = await require_services_organization_service.updatePlan(organization, {
68
- status,
69
- subscriptionId
70
- });
71
- if (!updatedOrganization) throw new require_utils_errors_ErrorsClass.GenericError("ORGANIZATION_UPDATE_FAILED", { organizationId: organization.id });
72
- const user = await require_services_user_service.getUserById(userId);
73
- if (!user) throw new require_utils_errors_ErrorsClass.GenericError("USER_NOT_FOUND", {
74
- userId,
75
- subscriptionId
76
- });
77
- require_logger_index.logger.info(`Updated plan status for organization ${organization.id} - Status: ${status}`);
78
- const emailData = {
79
- to: user.email,
80
- username: user.name,
81
- email: user.email,
82
- planName: organization.plan.type,
83
- date: (/* @__PURE__ */ new Date()).toLocaleDateString(),
84
- link: `${process.env.CLIENT_URL}/dashboard`
85
- };
86
- switch (status) {
87
- case "active":
88
- await require_services_email_service.sendEmail({
89
- ...emailData,
90
- type: "subscriptionPaymentSuccess",
91
- organizationName: organization.name,
92
- subscriptionStartDate: emailData.date,
93
- manageSubscriptionLink: emailData.link
94
- });
95
- break;
96
- case "canceled":
97
- await require_services_email_service.sendEmail({
98
- ...emailData,
99
- type: "subscriptionPaymentCancellation",
100
- organizationName: organization.name,
101
- cancellationDate: emailData.date,
102
- reactivateLink: emailData.link
103
- });
104
- break;
105
- case "incomplete":
106
- await require_services_email_service.sendEmail({
107
- ...emailData,
108
- type: "subscriptionPaymentError",
109
- organizationName: organization.name,
110
- errorDate: emailData.date,
111
- retryPaymentLink: emailData.link
112
- });
113
- break;
114
- default: require_logger_index.logger.warn(`Unhandled subscription status: ${status}`);
115
- }
116
- return updatedOrganization.plan ?? null;
117
- };
118
- const getCouponId = async (promoCode) => {
119
- const stripe$1 = new stripe.default(process.env.STRIPE_SECRET_KEY);
120
- try {
121
- const matchingCoupon = (await stripe$1.coupons.list()).data.find((coupon) => coupon.name === promoCode);
122
- return matchingCoupon ? matchingCoupon.id : null;
123
- } catch (error) {
124
- console.error("Error retrieving coupon:", error);
125
- return null;
126
- }
127
- };
128
- const getPricing = async (priceIds, promoCode) => {
129
- const stripe$1 = new stripe.default(process.env.STRIPE_SECRET_KEY);
130
- try {
131
- const pricePromises = priceIds.map((priceId) => stripe$1.prices.retrieve(priceId));
132
- const prices = await Promise.all(pricePromises);
133
- const totalAmount = prices.reduce((sum, price) => sum + (price.unit_amount ?? 0), 0);
134
- let discountAmount = 0;
135
- let discountType = null;
136
- if (promoCode) {
137
- const matchingCoupons = (await stripe$1.coupons.list()).data.find((coupon) => coupon.name === promoCode);
138
- if (matchingCoupons) {
139
- if (matchingCoupons.amount_off) {
140
- discountAmount = matchingCoupons.amount_off;
141
- discountType = "amount";
142
- } else if (matchingCoupons.percent_off) {
143
- discountAmount = matchingCoupons.percent_off;
144
- discountType = "percentage";
145
- }
146
- }
147
- }
148
- const results = {};
149
- for (const price of prices) {
150
- if (!price.id || !price.unit_amount) continue;
151
- const originalTotal = price.unit_amount;
152
- let appliedDiscount = 0;
153
- let finalTotal = originalTotal;
154
- if (discountType === "percentage" && discountAmount > 0) {
155
- appliedDiscount = originalTotal * discountAmount / 100;
156
- finalTotal = originalTotal - appliedDiscount;
157
- } else if (discountType === "amount" && totalAmount > 0 && discountAmount > 0) {
158
- const proportion = originalTotal / totalAmount;
159
- appliedDiscount = discountAmount * proportion;
160
- finalTotal = originalTotal - appliedDiscount;
161
- }
162
- finalTotal = Math.max(finalTotal, 0);
163
- results[price.id] = {
164
- originalTotal,
165
- discountApplied: appliedDiscount,
166
- discountType,
167
- finalTotal,
168
- currency: price.currency
169
- };
170
- }
171
- return results;
172
- } catch (error) {
173
- console.error("Error calculating pricing per priceId:", error);
174
- throw new Error("Failed to calculate pricing breakdown.");
175
- }
176
- };
177
-
178
- //#endregion
179
- exports.addOrUpdateSubscription = addOrUpdateSubscription;
180
- exports.cancelSubscription = cancelSubscription;
181
- exports.changeSubscriptionStatus = changeSubscriptionStatus;
182
- exports.getCouponId = getCouponId;
183
- exports.getPricing = getPricing;
184
- //# sourceMappingURL=subscription.service.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"subscription.service.cjs","names":["stripe","Stripe","getUserById","GenericError","retrievePlanInformation","updatePlan","getOrganizationById","sendEmail","discountType: 'amount' | 'percentage' | null","results: PricingResult"],"sources":["../../../src/services/subscription.service.ts"],"sourcesContent":["import { logger } from '@logger';\nimport { GenericError } from '@utils/errors';\nimport { retrievePlanInformation } from '@utils/plan';\nimport Stripe from 'stripe';\nimport type { Organization } from '@/types/organization.types';\nimport type { Plan } from '@/types/plan.types';\nimport { sendEmail } from './email.service';\nimport { getOrganizationById, updatePlan } from './organization.service';\nimport { getUserById } from './user.service';\n\nexport const addOrUpdateSubscription = async (\n subscriptionId: string,\n priceId: string,\n customerId: string,\n userId: string,\n organization: Organization,\n status: Plan['status']\n): Promise<Plan | null> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n const user = await getUserById(userId);\n\n if (!user) {\n throw new GenericError('USER_NOT_FOUND', {\n userId,\n });\n }\n\n if (String(user.customerId) !== customerId) {\n (user.customerId as unknown as string) = customerId;\n await user.save();\n }\n\n const planInfo = retrievePlanInformation(priceId);\n\n const subscriptions = await stripe.subscriptions.list({\n customer: customerId,\n status: 'active',\n limit: 1,\n });\n\n if (subscriptions.data.length >= 1) {\n // Active subscription exists; update it to the new plan\n const otherSubscriptionArray = subscriptions.data.filter(\n (subscription) => subscription.id !== subscriptionId\n );\n\n for (const subscription of otherSubscriptionArray) {\n await stripe.subscriptions.cancel(subscription.id);\n }\n }\n\n const updatedOrganization = await updatePlan(organization, {\n creatorId: user.id,\n priceId,\n customerId,\n subscriptionId,\n type: planInfo.type,\n period: planInfo.period,\n status,\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization.id,\n });\n }\n\n logger.info(\n `Plan updated for organization ${organization.id} - ${planInfo.type} - ${planInfo.period}`\n );\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const cancelSubscription = async (\n subscriptionId: string | Organization['id'],\n organizationId: Organization['id'] | string\n): Promise<Plan | null> => {\n const organization = await getOrganizationById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', {\n subscriptionId,\n });\n }\n\n if (!subscriptionId) {\n throw new GenericError('NO_SUBSCRIPTION_ID_PROVIDED');\n }\n\n if (!organization.plan) {\n throw new GenericError('ORGANIZATION_PLAN_NOT_FOUND', {\n subscriptionId,\n organizationId: organization.id,\n });\n }\n\n const updatedOrganization = await updatePlan(organization, {\n status: 'canceled',\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization.id,\n });\n }\n\n logger.info(\n `Cancelled plan for organization ${updatedOrganization.id} - ${updatedOrganization.plan?.type} - ${updatedOrganization.plan?.period}`\n );\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const changeSubscriptionStatus = async (\n subscriptionId: string,\n status: Plan['status'],\n userId: string,\n organizationId: string\n): Promise<Plan | null> => {\n const organization = await getOrganizationById(organizationId);\n\n if (!organization) {\n throw new GenericError('ORGANIZATION_NOT_FOUND', {\n userId,\n subscriptionId,\n });\n }\n\n if (!organization.plan) {\n throw new GenericError('ORGANIZATION_PLAN_NOT_FOUND', {\n userId,\n subscriptionId,\n organizationId: organization.id,\n });\n }\n\n const updatedOrganization = await updatePlan(organization, {\n status,\n subscriptionId,\n });\n\n if (!updatedOrganization) {\n throw new GenericError('ORGANIZATION_UPDATE_FAILED', {\n organizationId: organization.id,\n });\n }\n\n const user = await getUserById(userId);\n\n if (!user) {\n throw new GenericError('USER_NOT_FOUND', {\n userId,\n subscriptionId,\n });\n }\n\n logger.info(\n `Updated plan status for organization ${organization.id} - Status: ${status}`\n );\n\n const emailData = {\n to: user.email,\n username: user.name,\n email: user.email,\n planName: organization.plan.type,\n date: new Date().toLocaleDateString(),\n link: `${process.env.CLIENT_URL}/dashboard`,\n };\n\n switch (status) {\n case 'active':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentSuccess',\n organizationName: organization.name,\n subscriptionStartDate: emailData.date,\n manageSubscriptionLink: emailData.link,\n });\n break;\n case 'canceled':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentCancellation',\n organizationName: organization.name,\n cancellationDate: emailData.date,\n reactivateLink: emailData.link,\n });\n break;\n case 'incomplete':\n await sendEmail({\n ...emailData,\n type: 'subscriptionPaymentError',\n organizationName: organization.name,\n errorDate: emailData.date,\n retryPaymentLink: emailData.link,\n });\n break;\n default:\n logger.warn(`Unhandled subscription status: ${status}`);\n }\n\n return updatedOrganization.plan ?? null;\n};\n\nexport const getCouponId = async (\n promoCode: string\n): Promise<string | null> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n\n try {\n // Retrieve the coupon details by name\n const coupons = await stripe.coupons.list();\n const matchingCoupon = coupons.data.find(\n (coupon) => coupon.name === promoCode\n );\n\n return matchingCoupon ? matchingCoupon.id : null;\n } catch (error) {\n console.error('Error retrieving coupon:', error);\n return null;\n }\n};\n\nexport type PricingResult = Record<\n string,\n {\n originalTotal: number;\n discountApplied: number;\n discountType: 'amount' | 'percentage' | null;\n finalTotal: number;\n currency: string;\n }\n>;\n\nexport const getPricing = async (\n priceIds: string[],\n promoCode?: string\n): Promise<PricingResult> => {\n const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);\n\n try {\n // 1. Fetch all price objects\n const pricePromises = priceIds.map((priceId) =>\n stripe.prices.retrieve(priceId)\n );\n const prices = await Promise.all(pricePromises);\n\n // Calculate the total amount before discount (to help with proportional distribution if needed)\n const totalAmount = prices.reduce(\n (sum, price) => sum + (price.unit_amount ?? 0),\n 0\n );\n\n // 2. Retrieve the discount (if promo code is provided)\n let discountAmount = 0;\n let discountType: 'amount' | 'percentage' | null = null;\n\n if (promoCode) {\n const coupons = await stripe.coupons.list();\n const matchingCoupons = coupons.data.find(\n (coupon) => coupon.name === promoCode\n );\n if (matchingCoupons) {\n if (matchingCoupons.amount_off) {\n discountAmount = matchingCoupons.amount_off;\n discountType = 'amount';\n } else if (matchingCoupons.percent_off) {\n // For a percentage discount, we won't store discountAmount as a raw number\n // because each price line is discounted individually by the same percentage.\n discountAmount = matchingCoupons.percent_off;\n discountType = 'percentage';\n }\n }\n }\n\n // 3. Build the result for each priceId\n const results: PricingResult = {};\n\n for (const price of prices) {\n if (!price.id || !price.unit_amount) {\n continue; // Skip any invalid price\n }\n\n const originalTotal = price.unit_amount;\n let appliedDiscount = 0;\n let finalTotal = originalTotal;\n\n // Apply discount based on the discount type\n if (discountType === 'percentage' && discountAmount > 0) {\n // percentage-based discount\n appliedDiscount = (originalTotal * discountAmount) / 100;\n finalTotal = originalTotal - appliedDiscount;\n } else if (\n discountType === 'amount' &&\n totalAmount > 0 &&\n discountAmount > 0\n ) {\n // fixed amount discount - distribute proportionally\n const proportion = originalTotal / totalAmount;\n appliedDiscount = discountAmount * proportion;\n finalTotal = originalTotal - appliedDiscount;\n }\n\n // Prevent final total from going negative due to rounding\n finalTotal = Math.max(finalTotal, 0);\n\n results[price.id] = {\n originalTotal: originalTotal,\n discountApplied: appliedDiscount,\n discountType,\n finalTotal: finalTotal,\n currency: price.currency,\n };\n }\n\n return results;\n } catch (error) {\n console.error('Error calculating pricing per priceId:', error);\n throw new Error('Failed to calculate pricing breakdown.');\n }\n};\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,0BAA0B,OACrC,gBACA,SACA,YACA,QACA,cACA,WACyB;CACzB,MAAMA,WAAS,IAAIC,eAAO,QAAQ,IAAI,kBAAmB;CACz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,iBAAiB,GAAG;AAEvD,sBAAmB,gBAAgB,iBAAkB;AACrD,iBAAa,gBAAgB;cAE7B,iBAAiB,YACjB,cAAc,KACd,iBAAiB,GACjB;IAEA,MAAM,aAAa,gBAAgB;AACnC,sBAAkB,iBAAiB;AACnC,iBAAa,gBAAgB;;AAI/B,gBAAa,KAAK,IAAI,YAAY,EAAE;AAEpC,WAAQ,MAAM,MAAM;IACH;IACf,iBAAiB;IACjB;IACY;IACZ,UAAU,MAAM;IACjB;;AAGH,SAAO;UACA,OAAO;AACd,UAAQ,MAAM,0CAA0C,MAAM;AAC9D,QAAM,IAAI,MAAM,yCAAyC"}
@@ -1,88 +0,0 @@
1
- const require_utils_errors_ErrorsClass = require('../utils/errors/ErrorsClass.cjs');
2
- const require_utils_validation_validateTag = require('../utils/validation/validateTag.cjs');
3
- const require_models_tag_model = require('../models/tag.model.cjs');
4
-
5
- //#region src/services/tag.service.ts
6
- /**
7
- * Finds tags based on filters and pagination options.
8
- * @param filters - MongoDB filter query.
9
- * @param skip - Number of documents to skip.
10
- * @param limit - Number of documents to limit.
11
- * @returns List of tags matching the filters.
12
- */
13
- const findTags = async (filters, skip = 0, limit = 100, sortOptions) => {
14
- let query = require_models_tag_model.TagModel.find(filters).skip(skip).limit(limit);
15
- if (sortOptions && Object.keys(sortOptions).length > 0) query = query.sort(sortOptions);
16
- return await query;
17
- };
18
- /**
19
- * Finds a tag by its ID.
20
- * @param tagId - The ID of the tag to find.
21
- * @returns The tag matching the ID.
22
- */
23
- const getTagById = async (tagId) => {
24
- const tag = await require_models_tag_model.TagModel.findById(tagId);
25
- if (!tag) throw new require_utils_errors_ErrorsClass.GenericError("TAG_NOT_FOUND", { tagId });
26
- return tag;
27
- };
28
- const getTagsByKeys = async (keys, organizationId) => {
29
- return await require_models_tag_model.TagModel.find({
30
- key: { $in: keys },
31
- organizationId
32
- });
33
- };
34
- /**
35
- * Counts the total number of tags that match the filters.
36
- * @param filters - MongoDB filter query.
37
- * @returns Total number of tags.
38
- */
39
- const countTags = async (filters) => {
40
- const result = await require_models_tag_model.TagModel.countDocuments(filters);
41
- if (typeof result === "undefined") throw new require_utils_errors_ErrorsClass.GenericError("TAG_COUNT_FAILED", { filters });
42
- return result;
43
- };
44
- /**
45
- * Creates a new tag in the database.
46
- * @param tag - The tag data to create.
47
- * @returns The created tag.
48
- */
49
- const createTag = async (tag) => {
50
- const errors = await require_utils_validation_validateTag.validateTag(tag, ["key"]);
51
- if (Object.keys(errors).length > 0) throw new require_utils_errors_ErrorsClass.GenericError("TAG_INVALID_FIELDS", { errors });
52
- return await require_models_tag_model.TagModel.create(tag);
53
- };
54
- /**
55
- * Updates an existing tag in the database by its ID.
56
- * @param tagId - The ID of the tag to update.
57
- * @param tag - The updated tag data.
58
- * @returns The updated tag.
59
- */
60
- const updateTagById = async (tagId, tag) => {
61
- const errors = require_utils_validation_validateTag.validateTag(tag, Object.keys(tag));
62
- if (Object.keys(errors).length > 0) throw new require_utils_errors_ErrorsClass.GenericError("TAG_INVALID_FIELDS", {
63
- tagId,
64
- errors
65
- });
66
- if ((await require_models_tag_model.TagModel.updateOne({ _id: tagId }, tag)).matchedCount === 0) throw new require_utils_errors_ErrorsClass.GenericError("TAG_UPDATE_FAILED", { tagId });
67
- return await getTagById(tagId);
68
- };
69
- /**
70
- * Deletes a tag from the database by its ID.
71
- * @param tagId - The ID of the tag to delete.
72
- * @returns The result of the deletion operation.
73
- */
74
- const deleteTagById = async (tagId) => {
75
- const tag = await require_models_tag_model.TagModel.findByIdAndDelete(tagId);
76
- if (!tag) throw new require_utils_errors_ErrorsClass.GenericError("TAG_NOT_FOUND", { tagId });
77
- return tag;
78
- };
79
-
80
- //#endregion
81
- exports.countTags = countTags;
82
- exports.createTag = createTag;
83
- exports.deleteTagById = deleteTagById;
84
- exports.findTags = findTags;
85
- exports.getTagById = getTagById;
86
- exports.getTagsByKeys = getTagsByKeys;
87
- exports.updateTagById = updateTagById;
88
- //# sourceMappingURL=tag.service.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"tag.service.cjs","names":["TagModel","GenericError","validateTag"],"sources":["../../../src/services/tag.service.ts"],"sourcesContent":["import { TagModel } from '@models/tag.model';\nimport { GenericError } from '@utils/errors';\nimport type { TagFilters } from '@utils/filtersAndPagination/getTagFiltersAndPagination';\nimport { type TagFields, validateTag } from '@utils/validation/validateTag';\nimport type { Types } from 'mongoose';\nimport type { Organization } from '@/types/organization.types';\nimport type { Tag, TagData, TagDocument } from '@/types/tag.types';\n\n/**\n * Finds tags based on filters and pagination options.\n * @param filters - MongoDB filter query.\n * @param skip - Number of documents to skip.\n * @param limit - Number of documents to limit.\n * @returns List of tags matching the filters.\n */\nexport const findTags = async (\n filters: TagFilters,\n skip = 0,\n limit = 100,\n sortOptions?: Record<string, 1 | -1>\n): Promise<TagDocument[]> => {\n let query = TagModel.find(filters).skip(skip).limit(limit);\n\n if (sortOptions && Object.keys(sortOptions).length > 0) {\n query = query.sort(sortOptions);\n }\n\n return await query;\n};\n\n/**\n * Finds a tag by its ID.\n * @param tagId - The ID of the tag to find.\n * @returns The tag matching the ID.\n */\nexport const getTagById = async (\n tagId: string | Types.ObjectId\n): Promise<TagDocument> => {\n const tag = await TagModel.findById(tagId);\n\n if (!tag) {\n throw new GenericError('TAG_NOT_FOUND', { tagId });\n }\n\n return tag;\n};\n\nexport const getTagsByKeys = async (\n keys: string[],\n organizationId: string | Organization['id']\n): Promise<TagDocument[]> => {\n const tags = await TagModel.find({ key: { $in: keys }, organizationId });\n\n return tags;\n};\n\n/**\n * Counts the total number of tags that match the filters.\n * @param filters - MongoDB filter query.\n * @returns Total number of tags.\n */\nexport const countTags = async (filters: TagFilters): Promise<number> => {\n const result = await TagModel.countDocuments(filters);\n\n if (typeof result === 'undefined') {\n throw new GenericError('TAG_COUNT_FAILED', { filters });\n }\n\n return result;\n};\n\n/**\n * Creates a new tag in the database.\n * @param tag - The tag data to create.\n * @returns The created tag.\n */\nexport const createTag = async (tag: TagData): Promise<TagDocument> => {\n const errors = await validateTag(tag, ['key']);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('TAG_INVALID_FIELDS', { errors });\n }\n\n return await TagModel.create(tag);\n};\n\n/**\n * Updates an existing tag in the database by its ID.\n * @param tagId - The ID of the tag to update.\n * @param tag - The updated tag data.\n * @returns The updated tag.\n */\nexport const updateTagById = async (\n tagId: string | Types.ObjectId,\n tag: Partial<Tag>\n): Promise<TagDocument> => {\n const updatedKeys = Object.keys(tag) as TagFields;\n\n const errors = validateTag(tag, updatedKeys);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('TAG_INVALID_FIELDS', {\n tagId,\n errors,\n });\n }\n\n const result = await TagModel.updateOne({ _id: tagId }, tag);\n\n if (result.matchedCount === 0) {\n throw new GenericError('TAG_UPDATE_FAILED', { tagId });\n }\n\n return await getTagById(tagId);\n};\n\n/**\n * Deletes a tag from the database by its ID.\n * @param tagId - The ID of the tag to delete.\n * @returns The result of the deletion operation.\n */\nexport const deleteTagById = async (\n tagId: string | Types.ObjectId\n): Promise<TagDocument> => {\n const tag = await TagModel.findByIdAndDelete(tagId);\n\n if (!tag) {\n throw new GenericError('TAG_NOT_FOUND', { tagId });\n }\n\n return tag;\n};\n"],"mappings":";;;;;;;;;;;;AAeA,MAAa,WAAW,OACtB,SACA,OAAO,GACP,QAAQ,KACR,gBAC2B;CAC3B,IAAI,QAAQA,kCAAS,KAAK,QAAQ,CAAC,KAAK,KAAK,CAAC,MAAM,MAAM;AAE1D,KAAI,eAAe,OAAO,KAAK,YAAY,CAAC,SAAS,EACnD,SAAQ,MAAM,KAAK,YAAY;AAGjC,QAAO,MAAM;;;;;;;AAQf,MAAa,aAAa,OACxB,UACyB;CACzB,MAAM,MAAM,MAAMA,kCAAS,SAAS,MAAM;AAE1C,KAAI,CAAC,IACH,OAAM,IAAIC,8CAAa,iBAAiB,EAAE,OAAO,CAAC;AAGpD,QAAO;;AAGT,MAAa,gBAAgB,OAC3B,MACA,mBAC2B;AAG3B,QAFa,MAAMD,kCAAS,KAAK;EAAE,KAAK,EAAE,KAAK,MAAM;EAAE;EAAgB,CAAC;;;;;;;AAU1E,MAAa,YAAY,OAAO,YAAyC;CACvE,MAAM,SAAS,MAAMA,kCAAS,eAAe,QAAQ;AAErD,KAAI,OAAO,WAAW,YACpB,OAAM,IAAIC,8CAAa,oBAAoB,EAAE,SAAS,CAAC;AAGzD,QAAO;;;;;;;AAQT,MAAa,YAAY,OAAO,QAAuC;CACrE,MAAM,SAAS,MAAMC,iDAAY,KAAK,CAAC,MAAM,CAAC;AAE9C,KAAI,OAAO,KAAK,OAAO,CAAC,SAAS,EAC/B,OAAM,IAAID,8CAAa,sBAAsB,EAAE,QAAQ,CAAC;AAG1D,QAAO,MAAMD,kCAAS,OAAO,IAAI;;;;;;;;AASnC,MAAa,gBAAgB,OAC3B,OACA,QACyB;CAGzB,MAAM,SAASE,iDAAY,KAFP,OAAO,KAAK,IAAI,CAEQ;AAE5C,KAAI,OAAO,KAAK,OAAO,CAAC,SAAS,EAC/B,OAAM,IAAID,8CAAa,sBAAsB;EAC3C;EACA;EACD,CAAC;AAKJ,MAFe,MAAMD,kCAAS,UAAU,EAAE,KAAK,OAAO,EAAE,IAAI,EAEjD,iBAAiB,EAC1B,OAAM,IAAIC,8CAAa,qBAAqB,EAAE,OAAO,CAAC;AAGxD,QAAO,MAAM,WAAW,MAAM;;;;;;;AAQhC,MAAa,gBAAgB,OAC3B,UACyB;CACzB,MAAM,MAAM,MAAMD,kCAAS,kBAAkB,MAAM;AAEnD,KAAI,CAAC,IACH,OAAM,IAAIC,8CAAa,iBAAiB,EAAE,OAAO,CAAC;AAGpD,QAAO"}
@@ -1,120 +0,0 @@
1
- const require_utils_errors_ErrorsClass = require('../utils/errors/ErrorsClass.cjs');
2
- const require_utils_validation_validateUser = require('../utils/validation/validateUser.cjs');
3
- const require_models_user_model = require('../models/user.model.cjs');
4
-
5
- //#region src/services/user.service.ts
6
- /**
7
- * Creates a new user with password in the database and hashes the password.
8
- * @param user - User object with password not hashed.
9
- * @returns Created user object.
10
- */
11
- const createUser = async (user) => {
12
- const errors = require_utils_validation_validateUser.validateUser(user, ["email"]);
13
- if (Object.keys(errors).length > 0) throw new require_utils_errors_ErrorsClass.GenericError("USER_INVALID_FIELDS", {
14
- userEmail: user.email,
15
- errors
16
- });
17
- const newUser = await require_models_user_model.UserModel.create(user);
18
- if (!newUser) throw new require_utils_errors_ErrorsClass.GenericError("USER_CREATION_FAILED", { userEmail: user.email });
19
- return newUser;
20
- };
21
- /**
22
- * Retrieves a user by email.
23
- * @param email - User's email.
24
- * @returns User object or null if no user was found.
25
- */
26
- const getUserByEmail = async (email) => {
27
- return await require_models_user_model.UserModel.findOne({ email });
28
- };
29
- /**
30
- * Retrieves users list by email.
31
- * @param emails - Users email.
32
- * @returns User object or null if no user was found.
33
- */
34
- const getUsersByEmails = async (emails) => {
35
- return await require_models_user_model.UserModel.find({ email: { $in: emails } });
36
- };
37
- /**
38
- * Checks if a user exists by email.
39
- * @param email - User's email.
40
- * @returns True if the user exists, false otherwise.
41
- */
42
- const checkUserExists = async (email) => {
43
- return await require_models_user_model.UserModel.exists({ email }) !== null;
44
- };
45
- /**
46
- * Retrieves a user by ID.
47
- * @param userId - User's ID.
48
- * @returns User object or null if no user was found.
49
- */
50
- const getUserById = async (userId) => await require_models_user_model.UserModel.findById(userId);
51
- /**
52
- * Retrieves a user by ID.
53
- * @param userId - User's ID.
54
- * @returns User object or null if no user was found.
55
- */
56
- const getUsersByIds = async (userIds) => await require_models_user_model.UserModel.find({ _id: { $in: userIds } });
57
- /**
58
- * Finds users based on filters and pagination options.
59
- * @param filters - MongoDB filter query.
60
- * @param skip - Number of documents to skip.
61
- * @param limit - Number of documents to limit.
62
- * @param sortOptions - Sorting options.
63
- * @returns List of users matching the filters.
64
- */
65
- const findUsers = async (filters, skip, limit, sortOptions) => {
66
- let query = require_models_user_model.UserModel.find(filters).skip(skip).limit(limit);
67
- if (sortOptions && Object.keys(sortOptions).length > 0) query = query.sort(sortOptions);
68
- return await query;
69
- };
70
- /**
71
- * Counts the total number of users that match the filters.
72
- * @param filters - MongoDB filter query.
73
- * @returns Total number of users.
74
- */
75
- const countUsers = async (filters) => {
76
- const count = await require_models_user_model.UserModel.countDocuments(filters);
77
- if (typeof count === "undefined") throw new require_utils_errors_ErrorsClass.GenericError("USER_COUNT_FAILED");
78
- return count;
79
- };
80
- /**
81
- * Updates a user's information.
82
- * @param user - The user object.
83
- * @param updates - The updates to apply to the user.
84
- * @returns The updated user.
85
- */
86
- const updateUserById = async (userId, updates) => {
87
- const errors = require_utils_validation_validateUser.validateUser(updates, Object.keys(updates));
88
- if (Object.keys(errors).length > 0) throw new require_utils_errors_ErrorsClass.GenericError("USER_INVALID_FIELDS", {
89
- userId,
90
- errors
91
- });
92
- if ((await require_models_user_model.UserModel.updateOne({ _id: userId }, { $set: updates })).matchedCount === 0) throw new require_utils_errors_ErrorsClass.GenericError("USER_UPDATE_FAILED", { userId });
93
- const updatedUser = await require_models_user_model.UserModel.findById(userId);
94
- if (!updatedUser) throw new require_utils_errors_ErrorsClass.GenericError("USER_UPDATED_USER_NOT_FOUND", { userId });
95
- return updatedUser;
96
- };
97
- /**
98
- * Deletes a user from the database.
99
- * @param userId - The user object.
100
- * @returns
101
- */
102
- const deleteUser = async (userId) => {
103
- await getUserById(userId);
104
- const user = await require_models_user_model.UserModel.findByIdAndDelete(userId);
105
- if (!user) throw new require_utils_errors_ErrorsClass.GenericError("USER_NOT_FOUND", { userId });
106
- return user;
107
- };
108
-
109
- //#endregion
110
- exports.checkUserExists = checkUserExists;
111
- exports.countUsers = countUsers;
112
- exports.createUser = createUser;
113
- exports.deleteUser = deleteUser;
114
- exports.findUsers = findUsers;
115
- exports.getUserByEmail = getUserByEmail;
116
- exports.getUserById = getUserById;
117
- exports.getUsersByEmails = getUsersByEmails;
118
- exports.getUsersByIds = getUsersByIds;
119
- exports.updateUserById = updateUserById;
120
- //# sourceMappingURL=user.service.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"user.service.cjs","names":["validateUser","GenericError","newUser: UserDocument","UserModel"],"sources":["../../../src/services/user.service.ts"],"sourcesContent":["import { UserModel } from '@models/user.model';\nimport { GenericError } from '@utils/errors';\nimport type { UserFilters } from '@utils/filtersAndPagination/getUserFiltersAndPagination';\nimport {\n type FieldsToCheck,\n type UserFields,\n validateUser,\n} from '@utils/validation/validateUser';\nimport type { Types } from 'mongoose';\nimport type { User, UserAPI, UserDocument } from '@/types/user.types';\n\n/**\n * Creates a new user with password in the database and hashes the password.\n * @param user - User object with password not hashed.\n * @returns Created user object.\n */\nexport const createUser = async (\n user: Partial<User>\n): Promise<UserDocument> => {\n const fieldsToCheck: FieldsToCheck[] = ['email'];\n\n const errors = validateUser(user, fieldsToCheck);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('USER_INVALID_FIELDS', {\n userEmail: user.email,\n errors,\n });\n }\n\n const newUser: UserDocument = await UserModel.create(user);\n\n if (!newUser) {\n throw new GenericError('USER_CREATION_FAILED', { userEmail: user.email });\n }\n\n return newUser;\n};\n\n/**\n * Retrieves a user by email.\n * @param email - User's email.\n * @returns User object or null if no user was found.\n */\nexport const getUserByEmail = async (\n email: string\n): Promise<UserDocument | null> => {\n return await UserModel.findOne({ email });\n};\n\n/**\n * Retrieves users list by email.\n * @param emails - Users email.\n * @returns User object or null if no user was found.\n */\nexport const getUsersByEmails = async (\n emails: string[]\n): Promise<UserDocument[] | null> => {\n return await UserModel.find({ email: { $in: emails } });\n};\n\n/**\n * Checks if a user exists by email.\n * @param email - User's email.\n * @returns True if the user exists, false otherwise.\n */\nexport const checkUserExists = async (email: string): Promise<boolean> => {\n const user = await UserModel.exists({ email });\n return user !== null;\n};\n\n/**\n * Retrieves a user by ID.\n * @param userId - User's ID.\n * @returns User object or null if no user was found.\n */\nexport const getUserById = async (\n userId: string | Types.ObjectId\n): Promise<UserDocument | null> => await UserModel.findById(userId);\n\n/**\n * Retrieves a user by ID.\n * @param userId - User's ID.\n * @returns User object or null if no user was found.\n */\nexport const getUsersByIds = async (\n userIds: (string | Types.ObjectId)[]\n): Promise<UserDocument[] | null> =>\n await UserModel.find({ _id: { $in: userIds } });\n\n/**\n * Finds users based on filters and pagination options.\n * @param filters - MongoDB filter query.\n * @param skip - Number of documents to skip.\n * @param limit - Number of documents to limit.\n * @param sortOptions - Sorting options.\n * @returns List of users matching the filters.\n */\nexport const findUsers = async (\n filters: UserFilters,\n skip: number,\n limit: number,\n sortOptions?: Record<string, 1 | -1>\n): Promise<UserDocument[]> => {\n let query = UserModel.find(filters).skip(skip).limit(limit);\n\n if (sortOptions && Object.keys(sortOptions).length > 0) {\n query = query.sort(sortOptions);\n }\n\n return await query;\n};\n\n/**\n * Counts the total number of users that match the filters.\n * @param filters - MongoDB filter query.\n * @returns Total number of users.\n */\nexport const countUsers = async (filters: UserFilters): Promise<number> => {\n const count = await UserModel.countDocuments(filters);\n\n if (typeof count === 'undefined') {\n throw new GenericError('USER_COUNT_FAILED');\n }\n\n return count;\n};\n\n/**\n * Updates a user's information.\n * @param user - The user object.\n * @param updates - The updates to apply to the user.\n * @returns The updated user.\n */\nexport const updateUserById = async (\n userId: string | Types.ObjectId,\n updates: Partial<UserAPI>\n): Promise<UserDocument> => {\n const keyToValidate = Object.keys(updates) as UserFields;\n const errors = validateUser(updates, keyToValidate);\n\n if (Object.keys(errors).length > 0) {\n throw new GenericError('USER_INVALID_FIELDS', {\n userId,\n errors,\n });\n }\n\n const result = await UserModel.updateOne({ _id: userId }, { $set: updates });\n\n if (result.matchedCount === 0) {\n throw new GenericError('USER_UPDATE_FAILED', { userId });\n }\n\n const updatedUser = await UserModel.findById(userId);\n\n if (!updatedUser) {\n throw new GenericError('USER_UPDATED_USER_NOT_FOUND', { userId });\n }\n\n return updatedUser;\n};\n\n/**\n * Deletes a user from the database.\n * @param userId - The user object.\n * @returns\n */\nexport const deleteUser = async (\n userId: string | Types.ObjectId\n): Promise<UserDocument> => {\n await getUserById(userId);\n\n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AAU,eAAe,QAAQ;AAErD,KAAI,OAAO,UAAU,YACnB,OAAM,IAAIF,8CAAa,oBAAoB;AAG7C,QAAO;;;;;;;;AAST,MAAa,iBAAiB,OAC5B,QACA,YAC0B;CAE1B,MAAM,SAASD,mDAAa,SADN,OAAO,KAAK,QAAQ,CACS;AAEnD,KAAI,OAAO,KAAK,OAAO,CAAC,SAAS,EAC/B,OAAM,IAAIC,8CAAa,uBAAuB;EAC5C;EACA;EACD,CAAC;AAKJ,MAFe,MAAME,oCAAU,UAAU,EAAE,KAAK,QAAQ,EAAE,EAAE,MAAM,SAAS,CAAC,EAEjE,iBAAiB,EAC1B,OAAM,IAAIF,8CAAa,sBAAsB,EAAE,QAAQ,CAAC;CAG1D,MAAM,cAAc,MAAME,oCAAU,SAAS,OAAO;AAEpD,KAAI,CAAC,YACH,OAAM,IAAIF,8CAAa,+BAA+B,EAAE,QAAQ,CAAC;AAGnE,QAAO;;;;;;;AAQT,MAAa,aAAa,OACxB,WAC0B;AAC1B,OAAM,YAAY,OAAO;CAEzB,MAAM,OAAO,MAAME,oCAAU,kBAAkB,OAAO;AAEtD,KAAI,CAAC,KACH,OAAM,IAAIF,8CAAa,kBAAkB,EAAE,QAAQ,CAAC;AAGtD,QAAO"}
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -1,10 +0,0 @@
1
-
2
- //#region src/types/user.types.ts
3
- let EmailsList = /* @__PURE__ */ function(EmailsList$1) {
4
- EmailsList$1["NEWS_LETTER"] = "newsLetter";
5
- return EmailsList$1;
6
- }({});
7
-
8
- //#endregion
9
- exports.EmailsList = EmailsList;
10
- //# sourceMappingURL=user.types.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"user.types.cjs","names":[],"sources":["../../../src/types/user.types.ts"],"sourcesContent":["import type { RenameId } from '@utils/mongoDB/types';\nimport type { User as BetterAuthUser, OmitId } from 'better-auth';\nimport type { Document, Model, ObjectIdToString, Types } from 'mongoose';\n\nexport interface UserData {\n email: string;\n name: string;\n phone?: string;\n dateOfBirth?: Date;\n}\n\nexport enum EmailsList {\n NEWS_LETTER = 'newsLetter',\n}\n\nexport type User = OmitId<UserData & BetterAuthUser> & {\n id: Types.ObjectId;\n emailsList?: {\n [key in EmailsList]: boolean;\n };\n customerId?: string; // Stripe customer ID\n role?: string;\n lastLoginMethod?: 'email' | 'google' | 'github' | 'passkey';\n lang?: string;\n createdAt: Date;\n updatedAt: Date;\n};\n\nexport type UserAPI = ObjectIdToString<Omit<User, 'provider' | 'session'>>;\n\nexport type UserSchema = RenameId<User>;\nexport type UserModelType = Model<User>;\nexport type UserDocument = Document<unknown, {}, User> & User;\n"],"mappings":";;AAWA,IAAY,oDAAL;AACL"}
@@ -1,94 +0,0 @@
1
- const require_rolldown_runtime = require('../../_virtual/rolldown_runtime.cjs');
2
- let __ai_sdk_anthropic = require("@ai-sdk/anthropic");
3
- let __ai_sdk_deepseek = require("@ai-sdk/deepseek");
4
- let __ai_sdk_google = require("@ai-sdk/google");
5
- let __ai_sdk_mistral = require("@ai-sdk/mistral");
6
- let __ai_sdk_openai = require("@ai-sdk/openai");
7
-
8
- //#region src/utils/AI/aiSdk.ts
9
- /**
10
- * Supported AI SDK providers
11
- */
12
- let AIProvider = /* @__PURE__ */ function(AIProvider$1) {
13
- AIProvider$1["OPENAI"] = "openai";
14
- AIProvider$1["ANTHROPIC"] = "anthropic";
15
- AIProvider$1["MISTRAL"] = "mistral";
16
- AIProvider$1["DEEPSEEK"] = "deepseek";
17
- AIProvider$1["GEMINI"] = "gemini";
18
- return AIProvider$1;
19
- }({});
20
- const getAPIKey = (res, accessType, aiOptions) => {
21
- const defaultApiKey = process.env.OPENAI_API_KEY;
22
- if (accessType.includes("public")) return aiOptions?.apiKey ?? defaultApiKey;
23
- if (accessType.includes("apiKey") && aiOptions?.apiKey) return aiOptions?.apiKey;
24
- if (accessType.includes("registered_user") && res.locals.user) return aiOptions?.apiKey ?? defaultApiKey;
25
- if (accessType.includes("premium_user") && res.locals.user) return aiOptions?.apiKey ?? defaultApiKey;
26
- };
27
- const getModel = (provider, userApiKey, userModel, defaultModel = "gpt-5-mini") => {
28
- if (userApiKey) {
29
- if (provider && provider === AIProvider.OPENAI) return userModel;
30
- switch (provider) {
31
- case AIProvider.ANTHROPIC: return "claude-sonnet-4-5-20250929";
32
- case AIProvider.MISTRAL: return "mistral-large-latest";
33
- case AIProvider.DEEPSEEK: return "deepseek-coder";
34
- case AIProvider.GEMINI: return "gemini-2.5-flash";
35
- default: return defaultModel;
36
- }
37
- }
38
- if (userModel || provider) throw new Error("The user should use his own API key to use a custom model");
39
- return defaultModel;
40
- };
41
- const DEFAULT_PROVIDER = AIProvider.OPENAI;
42
- const DEFAULT_TEMPERATURE = 1;
43
- /**
44
- * Get AI model configuration based on the selected provider and options
45
- * This function handles the configuration for different AI providers
46
- *
47
- * @param options Configuration options including provider, API keys, models and temperature
48
- * @returns Configured AI model ready to use with generateText
49
- */
50
- const getAIConfig = async (res, options) => {
51
- const { userOptions, defaultOptions, accessType = ["registered_user"] } = options;
52
- const aiOptions = {
53
- provider: DEFAULT_PROVIDER,
54
- temperature: DEFAULT_TEMPERATURE,
55
- ...defaultOptions,
56
- ...userOptions
57
- };
58
- const apiKey = getAPIKey(res, accessType, aiOptions);
59
- if (!apiKey) throw new Error(`API key for ${aiOptions.provider} is missing`);
60
- const selectedModel = getModel(aiOptions.provider, apiKey, aiOptions.model, defaultOptions?.model);
61
- const protectedOptions = {
62
- ...aiOptions,
63
- apiKey,
64
- model: selectedModel
65
- };
66
- let languageModel;
67
- switch (protectedOptions.provider) {
68
- case AIProvider.OPENAI:
69
- languageModel = (0, __ai_sdk_openai.createOpenAI)({ apiKey })(selectedModel);
70
- break;
71
- case AIProvider.ANTHROPIC:
72
- languageModel = (0, __ai_sdk_anthropic.createAnthropic)({ apiKey })(selectedModel);
73
- break;
74
- case AIProvider.MISTRAL:
75
- languageModel = (0, __ai_sdk_mistral.createMistral)({ apiKey })(selectedModel);
76
- break;
77
- case AIProvider.DEEPSEEK:
78
- languageModel = (0, __ai_sdk_deepseek.createDeepSeek)({ apiKey })(selectedModel);
79
- break;
80
- case AIProvider.GEMINI:
81
- languageModel = (0, __ai_sdk_google.createGoogleGenerativeAI)({ apiKey })(selectedModel);
82
- break;
83
- default: throw new Error(`Provider ${protectedOptions.provider} not supported`);
84
- }
85
- return {
86
- model: languageModel,
87
- temperature: protectedOptions.temperature
88
- };
89
- };
90
-
91
- //#endregion
92
- exports.AIProvider = AIProvider;
93
- exports.getAIConfig = getAIConfig;
94
- //# sourceMappingURL=aiSdk.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"aiSdk.cjs","names":["DEFAULT_PROVIDER: AIProvider","DEFAULT_TEMPERATURE: number","languageModel: AIConfig['model']"],"sources":["../../../../src/utils/AI/aiSdk.ts"],"sourcesContent":["import { type anthropic, createAnthropic } from '@ai-sdk/anthropic';\nimport { createDeepSeek, type deepseek } from '@ai-sdk/deepseek';\nimport { createGoogleGenerativeAI, type google } from '@ai-sdk/google';\nimport { createMistral, type mistral } from '@ai-sdk/mistral';\nimport { createOpenAI, type openai } from '@ai-sdk/openai';\nimport type {\n AssistantModelMessage,\n generateText,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from 'ai';\nimport type { Response } from 'express';\n\ntype AnthropicModel = Parameters<typeof anthropic>[0];\ntype DeepSeekModel = Parameters<typeof deepseek>[0];\ntype MistralModel = Parameters<typeof mistral>[0];\ntype OpenAIModel = Parameters<typeof openai>[0];\ntype GoogleModel = Parameters<typeof google>[0];\n\nexport type Messages = (\n | SystemModelMessage\n | UserModelMessage\n | AssistantModelMessage\n | ToolModelMessage\n)[];\n\n/**\n * Supported AI models\n */\nexport type Model =\n | AnthropicModel\n | DeepSeekModel\n | MistralModel\n | OpenAIModel\n | GoogleModel\n | (string & {});\n\n/**\n * Supported AI SDK providers\n */\nexport enum AIProvider {\n OPENAI = 'openai',\n ANTHROPIC = 'anthropic',\n MISTRAL = 'mistral',\n DEEPSEEK = 'deepseek',\n GEMINI = 'gemini',\n}\n\n/**\n * Common options for all AI providers\n */\nexport type AIOptions = {\n provider?: AIProvider;\n model?: Model;\n temperature?: number;\n apiKey?: string;\n applicationContext?: string;\n};\n\n// Define the structure of messages used in chat completions\nexport type ChatCompletionRequestMessage = {\n role: 'system' | 'user' | 'assistant'; // The role of the message sender\n content: string; // The text content of the message\n timestamp?: Date; // The timestamp of the message\n};\n\ntype AccessType = 'apiKey' | 'registered_user' | 'premium_user' | 'public';\n\nconst getAPIKey = (\n res: Response,\n accessType: AccessType[],\n aiOptions?: AIOptions\n) => {\n const defaultApiKey = process.env.OPENAI_API_KEY;\n\n if (accessType.includes('public')) {\n return aiOptions?.apiKey ?? defaultApiKey;\n }\n\n if (accessType.includes('apiKey') && aiOptions?.apiKey) {\n return aiOptions?.apiKey;\n }\n\n if (accessType.includes('registered_user') && res.locals.user) {\n return aiOptions?.apiKey ?? defaultApiKey;\n }\n\n // TODO: Implement premium user access\n if (accessType.includes('premium_user') && res.locals.user) {\n return aiOptions?.apiKey ?? defaultApiKey;\n }\n\n return undefined;\n};\n\nconst getModel = (\n provider: AIProvider,\n userApiKey: string,\n userModel?: Model,\n defaultModel: Model = 'gpt-5-mini'\n): Model => {\n // If the user uses their own API key, allow custom model selection\n if (userApiKey) {\n if (provider && provider === AIProvider.OPENAI) {\n return userModel!;\n }\n\n switch (provider) {\n case AIProvider.ANTHROPIC:\n return 'claude-sonnet-4-5-20250929';\n case AIProvider.MISTRAL:\n return 'mistral-large-latest';\n case AIProvider.DEEPSEEK:\n return 'deepseek-coder';\n case AIProvider.GEMINI:\n return 'gemini-2.5-flash';\n default:\n return defaultModel;\n }\n }\n\n // Guard: Prevent custom model usage without a user API key\n if (userModel || provider) {\n throw new Error(\n 'The user should use his own API key to use a custom model'\n );\n }\n\n return defaultModel;\n};\n\nexport type AIConfig = Omit<Parameters<typeof generateText>[0], 'prompt'>;\n\nconst DEFAULT_PROVIDER: AIProvider = AIProvider.OPENAI as AIProvider;\nconst DEFAULT_TEMPERATURE: number = 1; // ChatGPT 5 accept only temperature 1\n\nexport type AIConfigOptions = {\n userOptions?: AIOptions;\n defaultOptions?: AIOptions;\n accessType?: AccessType[];\n};\n\n/**\n * Get AI model configuration based on the selected provider and options\n * This function handles the configuration for different AI providers\n *\n * @param options Configuration options including provider, API keys, models and temperature\n * @returns Configured AI model ready to use with generateText\n */\nexport const getAIConfig = async (\n res: Response,\n options: AIConfigOptions\n): Promise<AIConfig> => {\n const {\n userOptions,\n defaultOptions,\n accessType = ['registered_user'],\n } = options;\n\n const aiOptions = {\n provider: DEFAULT_PROVIDER,\n temperature: DEFAULT_TEMPERATURE,\n ...defaultOptions,\n ...userOptions,\n } satisfies AIOptions;\n\n const apiKey = getAPIKey(res, accessType, aiOptions);\n\n // Check if API key is provided\n if (!apiKey) {\n throw new Error(`API key for ${aiOptions.provider} is missing`);\n }\n\n const selectedModel = getModel(\n aiOptions.provider,\n apiKey,\n aiOptions.model,\n defaultOptions?.model\n );\n\n const protectedOptions = {\n ...aiOptions,\n apiKey,\n model: selectedModel,\n } satisfies AIOptions;\n\n let languageModel: AIConfig['model'];\n\n switch (protectedOptions.provider) {\n case AIProvider.OPENAI: {\n languageModel = createOpenAI({\n apiKey,\n })(selectedModel);\n break;\n }\n\n case AIProvider.ANTHROPIC: {\n languageModel = createAnthropic({\n apiKey,\n })(selectedModel);\n break;\n }\n\n case AIProvider.MISTRAL: {\n languageModel = createMistral({\n apiKey,\n })(selectedModel);\n break;\n }\n\n case AIProvider.DEEPSEEK: {\n languageModel = createDeepSeek({\n apiKey,\n })(selectedModel);\n break;\n }\n\n case AIProvider.GEMINI: {\n languageModel = createGoogleGenerativeAI({\n apiKey,\n })(selectedModel);\n break;\n }\n\n default: {\n throw new Error(`Provider ${protectedOptions.provider} not supported`);\n }\n }\n\n return {\n model: languageModel,\n temperature: protectedOptions.temperature,\n };\n};\n"],"mappings":";;;;;;;;;;;AAyC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