@hammadj/better-auth-core 1.5.0-beta.9

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 (353) hide show
  1. package/.turbo/turbo-build.log +266 -0
  2. package/.turbo/turbo-test.log +2 -0
  3. package/LICENSE.md +20 -0
  4. package/dist/api/index.d.mts +181 -0
  5. package/dist/api/index.mjs +34 -0
  6. package/dist/api/index.mjs.map +1 -0
  7. package/dist/async_hooks/index.d.mts +7 -0
  8. package/dist/async_hooks/index.mjs +22 -0
  9. package/dist/async_hooks/index.mjs.map +1 -0
  10. package/dist/async_hooks/pure.index.d.mts +7 -0
  11. package/dist/async_hooks/pure.index.mjs +35 -0
  12. package/dist/async_hooks/pure.index.mjs.map +1 -0
  13. package/dist/context/endpoint-context.d.mts +19 -0
  14. package/dist/context/endpoint-context.mjs +32 -0
  15. package/dist/context/endpoint-context.mjs.map +1 -0
  16. package/dist/context/global.d.mts +7 -0
  17. package/dist/context/global.mjs +38 -0
  18. package/dist/context/global.mjs.map +1 -0
  19. package/dist/context/index.d.mts +5 -0
  20. package/dist/context/index.mjs +6 -0
  21. package/dist/context/request-state.d.mts +26 -0
  22. package/dist/context/request-state.mjs +50 -0
  23. package/dist/context/request-state.mjs.map +1 -0
  24. package/dist/context/transaction.d.mts +25 -0
  25. package/dist/context/transaction.mjs +96 -0
  26. package/dist/context/transaction.mjs.map +1 -0
  27. package/dist/db/adapter/factory.d.mts +28 -0
  28. package/dist/db/adapter/factory.mjs +716 -0
  29. package/dist/db/adapter/factory.mjs.map +1 -0
  30. package/dist/db/adapter/get-default-field-name.d.mts +19 -0
  31. package/dist/db/adapter/get-default-field-name.mjs +39 -0
  32. package/dist/db/adapter/get-default-field-name.mjs.map +1 -0
  33. package/dist/db/adapter/get-default-model-name.d.mts +13 -0
  34. package/dist/db/adapter/get-default-model-name.mjs +33 -0
  35. package/dist/db/adapter/get-default-model-name.mjs.map +1 -0
  36. package/dist/db/adapter/get-field-attributes.d.mts +30 -0
  37. package/dist/db/adapter/get-field-attributes.mjs +40 -0
  38. package/dist/db/adapter/get-field-attributes.mjs.map +1 -0
  39. package/dist/db/adapter/get-field-name.d.mts +19 -0
  40. package/dist/db/adapter/get-field-name.mjs +34 -0
  41. package/dist/db/adapter/get-field-name.mjs.map +1 -0
  42. package/dist/db/adapter/get-id-field.d.mts +40 -0
  43. package/dist/db/adapter/get-id-field.mjs +68 -0
  44. package/dist/db/adapter/get-id-field.mjs.map +1 -0
  45. package/dist/db/adapter/get-model-name.d.mts +13 -0
  46. package/dist/db/adapter/get-model-name.mjs +24 -0
  47. package/dist/db/adapter/get-model-name.mjs.map +1 -0
  48. package/dist/db/adapter/index.d.mts +515 -0
  49. package/dist/db/adapter/index.mjs +10 -0
  50. package/dist/db/adapter/types.d.mts +140 -0
  51. package/dist/db/adapter/utils.d.mts +8 -0
  52. package/dist/db/adapter/utils.mjs +39 -0
  53. package/dist/db/adapter/utils.mjs.map +1 -0
  54. package/dist/db/get-tables.d.mts +9 -0
  55. package/dist/db/get-tables.mjs +267 -0
  56. package/dist/db/get-tables.mjs.map +1 -0
  57. package/dist/db/index.d.mts +10 -0
  58. package/dist/db/index.mjs +9 -0
  59. package/dist/db/plugin.d.mts +13 -0
  60. package/dist/db/schema/account.d.mts +27 -0
  61. package/dist/db/schema/account.mjs +20 -0
  62. package/dist/db/schema/account.mjs.map +1 -0
  63. package/dist/db/schema/rate-limit.d.mts +15 -0
  64. package/dist/db/schema/rate-limit.mjs +12 -0
  65. package/dist/db/schema/rate-limit.mjs.map +1 -0
  66. package/dist/db/schema/session.d.mts +22 -0
  67. package/dist/db/schema/session.mjs +15 -0
  68. package/dist/db/schema/session.mjs.map +1 -0
  69. package/dist/db/schema/shared.d.mts +11 -0
  70. package/dist/db/schema/shared.mjs +12 -0
  71. package/dist/db/schema/shared.mjs.map +1 -0
  72. package/dist/db/schema/user.d.mts +21 -0
  73. package/dist/db/schema/user.mjs +14 -0
  74. package/dist/db/schema/user.mjs.map +1 -0
  75. package/dist/db/schema/verification.d.mts +20 -0
  76. package/dist/db/schema/verification.mjs +13 -0
  77. package/dist/db/schema/verification.mjs.map +1 -0
  78. package/dist/db/type.d.mts +147 -0
  79. package/dist/env/color-depth.d.mts +5 -0
  80. package/dist/env/color-depth.mjs +89 -0
  81. package/dist/env/color-depth.mjs.map +1 -0
  82. package/dist/env/env-impl.d.mts +33 -0
  83. package/dist/env/env-impl.mjs +83 -0
  84. package/dist/env/env-impl.mjs.map +1 -0
  85. package/dist/env/index.d.mts +4 -0
  86. package/dist/env/index.mjs +5 -0
  87. package/dist/env/logger.d.mts +49 -0
  88. package/dist/env/logger.mjs +82 -0
  89. package/dist/env/logger.mjs.map +1 -0
  90. package/dist/error/codes.d.mts +199 -0
  91. package/dist/error/codes.mjs +57 -0
  92. package/dist/error/codes.mjs.map +1 -0
  93. package/dist/error/index.d.mts +20 -0
  94. package/dist/error/index.mjs +30 -0
  95. package/dist/error/index.mjs.map +1 -0
  96. package/dist/index.d.mts +8 -0
  97. package/dist/index.mjs +1 -0
  98. package/dist/oauth2/client-credentials-token.d.mts +37 -0
  99. package/dist/oauth2/client-credentials-token.mjs +55 -0
  100. package/dist/oauth2/client-credentials-token.mjs.map +1 -0
  101. package/dist/oauth2/create-authorization-url.d.mts +46 -0
  102. package/dist/oauth2/create-authorization-url.mjs +43 -0
  103. package/dist/oauth2/create-authorization-url.mjs.map +1 -0
  104. package/dist/oauth2/index.d.mts +8 -0
  105. package/dist/oauth2/index.mjs +8 -0
  106. package/dist/oauth2/oauth-provider.d.mts +195 -0
  107. package/dist/oauth2/refresh-access-token.d.mts +36 -0
  108. package/dist/oauth2/refresh-access-token.mjs +59 -0
  109. package/dist/oauth2/refresh-access-token.mjs.map +1 -0
  110. package/dist/oauth2/utils.d.mts +8 -0
  111. package/dist/oauth2/utils.mjs +28 -0
  112. package/dist/oauth2/utils.mjs.map +1 -0
  113. package/dist/oauth2/validate-authorization-code.d.mts +56 -0
  114. package/dist/oauth2/validate-authorization-code.mjs +72 -0
  115. package/dist/oauth2/validate-authorization-code.mjs.map +1 -0
  116. package/dist/oauth2/verify.d.mts +43 -0
  117. package/dist/oauth2/verify.mjs +96 -0
  118. package/dist/oauth2/verify.mjs.map +1 -0
  119. package/dist/social-providers/apple.d.mts +120 -0
  120. package/dist/social-providers/apple.mjs +105 -0
  121. package/dist/social-providers/apple.mjs.map +1 -0
  122. package/dist/social-providers/atlassian.d.mts +73 -0
  123. package/dist/social-providers/atlassian.mjs +84 -0
  124. package/dist/social-providers/atlassian.mjs.map +1 -0
  125. package/dist/social-providers/cognito.d.mts +88 -0
  126. package/dist/social-providers/cognito.mjs +166 -0
  127. package/dist/social-providers/cognito.mjs.map +1 -0
  128. package/dist/social-providers/discord.d.mts +127 -0
  129. package/dist/social-providers/discord.mjs +65 -0
  130. package/dist/social-providers/discord.mjs.map +1 -0
  131. package/dist/social-providers/dropbox.d.mts +72 -0
  132. package/dist/social-providers/dropbox.mjs +76 -0
  133. package/dist/social-providers/dropbox.mjs.map +1 -0
  134. package/dist/social-providers/facebook.d.mts +82 -0
  135. package/dist/social-providers/facebook.mjs +121 -0
  136. package/dist/social-providers/facebook.mjs.map +1 -0
  137. package/dist/social-providers/figma.d.mts +64 -0
  138. package/dist/social-providers/figma.mjs +87 -0
  139. package/dist/social-providers/figma.mjs.map +1 -0
  140. package/dist/social-providers/github.d.mts +105 -0
  141. package/dist/social-providers/github.mjs +97 -0
  142. package/dist/social-providers/github.mjs.map +1 -0
  143. package/dist/social-providers/gitlab.d.mts +126 -0
  144. package/dist/social-providers/gitlab.mjs +83 -0
  145. package/dist/social-providers/gitlab.mjs.map +1 -0
  146. package/dist/social-providers/google.d.mts +100 -0
  147. package/dist/social-providers/google.mjs +109 -0
  148. package/dist/social-providers/google.mjs.map +1 -0
  149. package/dist/social-providers/huggingface.d.mts +86 -0
  150. package/dist/social-providers/huggingface.mjs +76 -0
  151. package/dist/social-providers/huggingface.mjs.map +1 -0
  152. package/dist/social-providers/index.d.mts +1725 -0
  153. package/dist/social-providers/index.mjs +77 -0
  154. package/dist/social-providers/index.mjs.map +1 -0
  155. package/dist/social-providers/kakao.d.mts +164 -0
  156. package/dist/social-providers/kakao.mjs +73 -0
  157. package/dist/social-providers/kakao.mjs.map +1 -0
  158. package/dist/social-providers/kick.d.mts +76 -0
  159. package/dist/social-providers/kick.mjs +72 -0
  160. package/dist/social-providers/kick.mjs.map +1 -0
  161. package/dist/social-providers/line.d.mts +108 -0
  162. package/dist/social-providers/line.mjs +114 -0
  163. package/dist/social-providers/line.mjs.map +1 -0
  164. package/dist/social-providers/linear.d.mts +71 -0
  165. package/dist/social-providers/linear.mjs +89 -0
  166. package/dist/social-providers/linear.mjs.map +1 -0
  167. package/dist/social-providers/linkedin.d.mts +70 -0
  168. package/dist/social-providers/linkedin.mjs +77 -0
  169. package/dist/social-providers/linkedin.mjs.map +1 -0
  170. package/dist/social-providers/microsoft-entra-id.d.mts +175 -0
  171. package/dist/social-providers/microsoft-entra-id.mjs +107 -0
  172. package/dist/social-providers/microsoft-entra-id.mjs.map +1 -0
  173. package/dist/social-providers/naver.d.mts +95 -0
  174. package/dist/social-providers/naver.mjs +68 -0
  175. package/dist/social-providers/naver.mjs.map +1 -0
  176. package/dist/social-providers/notion.d.mts +67 -0
  177. package/dist/social-providers/notion.mjs +76 -0
  178. package/dist/social-providers/notion.mjs.map +1 -0
  179. package/dist/social-providers/paybin.d.mts +74 -0
  180. package/dist/social-providers/paybin.mjs +86 -0
  181. package/dist/social-providers/paybin.mjs.map +1 -0
  182. package/dist/social-providers/paypal.d.mts +132 -0
  183. package/dist/social-providers/paypal.mjs +145 -0
  184. package/dist/social-providers/paypal.mjs.map +1 -0
  185. package/dist/social-providers/polar.d.mts +77 -0
  186. package/dist/social-providers/polar.mjs +74 -0
  187. package/dist/social-providers/polar.mjs.map +1 -0
  188. package/dist/social-providers/reddit.d.mts +65 -0
  189. package/dist/social-providers/reddit.mjs +84 -0
  190. package/dist/social-providers/reddit.mjs.map +1 -0
  191. package/dist/social-providers/roblox.d.mts +73 -0
  192. package/dist/social-providers/roblox.mjs +60 -0
  193. package/dist/social-providers/roblox.mjs.map +1 -0
  194. package/dist/social-providers/salesforce.d.mts +82 -0
  195. package/dist/social-providers/salesforce.mjs +92 -0
  196. package/dist/social-providers/salesforce.mjs.map +1 -0
  197. package/dist/social-providers/slack.d.mts +86 -0
  198. package/dist/social-providers/slack.mjs +69 -0
  199. package/dist/social-providers/slack.mjs.map +1 -0
  200. package/dist/social-providers/spotify.d.mts +66 -0
  201. package/dist/social-providers/spotify.mjs +72 -0
  202. package/dist/social-providers/spotify.mjs.map +1 -0
  203. package/dist/social-providers/tiktok.d.mts +171 -0
  204. package/dist/social-providers/tiktok.mjs +63 -0
  205. package/dist/social-providers/tiktok.mjs.map +1 -0
  206. package/dist/social-providers/twitch.d.mts +82 -0
  207. package/dist/social-providers/twitch.mjs +79 -0
  208. package/dist/social-providers/twitch.mjs.map +1 -0
  209. package/dist/social-providers/twitter.d.mts +129 -0
  210. package/dist/social-providers/twitter.mjs +88 -0
  211. package/dist/social-providers/twitter.mjs.map +1 -0
  212. package/dist/social-providers/vercel.d.mts +65 -0
  213. package/dist/social-providers/vercel.mjs +62 -0
  214. package/dist/social-providers/vercel.mjs.map +1 -0
  215. package/dist/social-providers/vk.d.mts +73 -0
  216. package/dist/social-providers/vk.mjs +84 -0
  217. package/dist/social-providers/vk.mjs.map +1 -0
  218. package/dist/social-providers/zoom.d.mts +173 -0
  219. package/dist/social-providers/zoom.mjs +73 -0
  220. package/dist/social-providers/zoom.mjs.map +1 -0
  221. package/dist/types/context.d.mts +267 -0
  222. package/dist/types/cookie.d.mts +16 -0
  223. package/dist/types/helper.d.mts +10 -0
  224. package/dist/types/index.d.mts +8 -0
  225. package/dist/types/init-options.d.mts +1314 -0
  226. package/dist/types/plugin-client.d.mts +112 -0
  227. package/dist/types/plugin.d.mts +125 -0
  228. package/dist/utils/db.d.mts +12 -0
  229. package/dist/utils/db.mjs +17 -0
  230. package/dist/utils/db.mjs.map +1 -0
  231. package/dist/utils/deprecate.d.mts +10 -0
  232. package/dist/utils/deprecate.mjs +18 -0
  233. package/dist/utils/deprecate.mjs.map +1 -0
  234. package/dist/utils/error-codes.d.mts +13 -0
  235. package/dist/utils/error-codes.mjs +12 -0
  236. package/dist/utils/error-codes.mjs.map +1 -0
  237. package/dist/utils/id.d.mts +5 -0
  238. package/dist/utils/id.mjs +10 -0
  239. package/dist/utils/id.mjs.map +1 -0
  240. package/dist/utils/ip.d.mts +55 -0
  241. package/dist/utils/ip.mjs +119 -0
  242. package/dist/utils/ip.mjs.map +1 -0
  243. package/dist/utils/json.d.mts +5 -0
  244. package/dist/utils/json.mjs +26 -0
  245. package/dist/utils/json.mjs.map +1 -0
  246. package/dist/utils/string.d.mts +5 -0
  247. package/dist/utils/string.mjs +8 -0
  248. package/dist/utils/string.mjs.map +1 -0
  249. package/dist/utils/url.d.mts +21 -0
  250. package/dist/utils/url.mjs +33 -0
  251. package/dist/utils/url.mjs.map +1 -0
  252. package/package.json +147 -0
  253. package/src/api/index.ts +106 -0
  254. package/src/async_hooks/index.ts +40 -0
  255. package/src/async_hooks/pure.index.ts +46 -0
  256. package/src/context/endpoint-context.ts +50 -0
  257. package/src/context/global.ts +57 -0
  258. package/src/context/index.ts +23 -0
  259. package/src/context/request-state.test.ts +94 -0
  260. package/src/context/request-state.ts +91 -0
  261. package/src/context/transaction.ts +136 -0
  262. package/src/db/adapter/factory.ts +1362 -0
  263. package/src/db/adapter/get-default-field-name.ts +59 -0
  264. package/src/db/adapter/get-default-model-name.ts +51 -0
  265. package/src/db/adapter/get-field-attributes.ts +62 -0
  266. package/src/db/adapter/get-field-name.ts +43 -0
  267. package/src/db/adapter/get-id-field.ts +141 -0
  268. package/src/db/adapter/get-model-name.ts +36 -0
  269. package/src/db/adapter/index.ts +554 -0
  270. package/src/db/adapter/types.ts +171 -0
  271. package/src/db/adapter/utils.ts +61 -0
  272. package/src/db/get-tables.ts +296 -0
  273. package/src/db/index.ts +18 -0
  274. package/src/db/plugin.ts +11 -0
  275. package/src/db/schema/account.ts +34 -0
  276. package/src/db/schema/rate-limit.ts +21 -0
  277. package/src/db/schema/session.ts +17 -0
  278. package/src/db/schema/shared.ts +7 -0
  279. package/src/db/schema/user.ts +16 -0
  280. package/src/db/schema/verification.ts +15 -0
  281. package/src/db/test/get-tables.test.ts +116 -0
  282. package/src/db/type.ts +180 -0
  283. package/src/env/color-depth.ts +172 -0
  284. package/src/env/env-impl.ts +124 -0
  285. package/src/env/index.ts +23 -0
  286. package/src/env/logger.test.ts +34 -0
  287. package/src/env/logger.ts +145 -0
  288. package/src/error/codes.ts +58 -0
  289. package/src/error/index.ts +35 -0
  290. package/src/index.ts +1 -0
  291. package/src/oauth2/client-credentials-token.ts +102 -0
  292. package/src/oauth2/create-authorization-url.ts +87 -0
  293. package/src/oauth2/index.ts +26 -0
  294. package/src/oauth2/oauth-provider.ts +222 -0
  295. package/src/oauth2/refresh-access-token.ts +124 -0
  296. package/src/oauth2/utils.ts +38 -0
  297. package/src/oauth2/validate-authorization-code.ts +149 -0
  298. package/src/oauth2/validate-token.test.ts +174 -0
  299. package/src/oauth2/verify.ts +221 -0
  300. package/src/social-providers/apple.ts +223 -0
  301. package/src/social-providers/atlassian.ts +132 -0
  302. package/src/social-providers/cognito.ts +279 -0
  303. package/src/social-providers/discord.ts +169 -0
  304. package/src/social-providers/dropbox.ts +112 -0
  305. package/src/social-providers/facebook.ts +206 -0
  306. package/src/social-providers/figma.ts +117 -0
  307. package/src/social-providers/github.ts +184 -0
  308. package/src/social-providers/gitlab.ts +155 -0
  309. package/src/social-providers/google.ts +199 -0
  310. package/src/social-providers/huggingface.ts +118 -0
  311. package/src/social-providers/index.ts +127 -0
  312. package/src/social-providers/kakao.ts +178 -0
  313. package/src/social-providers/kick.ts +109 -0
  314. package/src/social-providers/line.ts +169 -0
  315. package/src/social-providers/linear.ts +121 -0
  316. package/src/social-providers/linkedin.ts +110 -0
  317. package/src/social-providers/microsoft-entra-id.ts +259 -0
  318. package/src/social-providers/naver.ts +112 -0
  319. package/src/social-providers/notion.ts +108 -0
  320. package/src/social-providers/paybin.ts +122 -0
  321. package/src/social-providers/paypal.ts +263 -0
  322. package/src/social-providers/polar.ts +110 -0
  323. package/src/social-providers/reddit.ts +122 -0
  324. package/src/social-providers/roblox.ts +111 -0
  325. package/src/social-providers/salesforce.ts +159 -0
  326. package/src/social-providers/slack.ts +111 -0
  327. package/src/social-providers/spotify.ts +93 -0
  328. package/src/social-providers/tiktok.ts +209 -0
  329. package/src/social-providers/twitch.ts +111 -0
  330. package/src/social-providers/twitter.ts +198 -0
  331. package/src/social-providers/vercel.ts +87 -0
  332. package/src/social-providers/vk.ts +124 -0
  333. package/src/social-providers/zoom.ts +238 -0
  334. package/src/types/context.ts +396 -0
  335. package/src/types/cookie.ts +10 -0
  336. package/src/types/helper.ts +26 -0
  337. package/src/types/index.ts +32 -0
  338. package/src/types/init-options.ts +1529 -0
  339. package/src/types/plugin-client.ts +127 -0
  340. package/src/types/plugin.ts +157 -0
  341. package/src/utils/db.ts +20 -0
  342. package/src/utils/deprecate.test.ts +72 -0
  343. package/src/utils/deprecate.ts +21 -0
  344. package/src/utils/error-codes.ts +65 -0
  345. package/src/utils/id.ts +5 -0
  346. package/src/utils/ip.test.ts +255 -0
  347. package/src/utils/ip.ts +211 -0
  348. package/src/utils/json.ts +25 -0
  349. package/src/utils/string.ts +3 -0
  350. package/src/utils/url.ts +43 -0
  351. package/tsconfig.json +7 -0
  352. package/tsdown.config.ts +35 -0
  353. package/vitest.config.ts +3 -0
@@ -0,0 +1,1362 @@
1
+ import { createLogger, getColorDepth, TTY_COLORS } from "../../env";
2
+ import { BetterAuthError } from "../../error";
3
+ import type { BetterAuthOptions } from "../../types";
4
+ import { safeJSONParse } from "../../utils/json";
5
+ import { getAuthTables } from "../get-tables";
6
+ import { initGetDefaultFieldName } from "./get-default-field-name";
7
+ import { initGetDefaultModelName } from "./get-default-model-name";
8
+ import { initGetFieldAttributes } from "./get-field-attributes";
9
+ import { initGetFieldName } from "./get-field-name";
10
+ import { initGetIdField } from "./get-id-field";
11
+ import { initGetModelName } from "./get-model-name";
12
+ import type {
13
+ CleanedWhere,
14
+ DBAdapter,
15
+ DBTransactionAdapter,
16
+ JoinConfig,
17
+ JoinOption,
18
+ Where,
19
+ } from "./index";
20
+ import type {
21
+ AdapterFactoryConfig,
22
+ AdapterFactoryOptions,
23
+ AdapterTestDebugLogs,
24
+ } from "./types";
25
+ import { withApplyDefault } from "./utils";
26
+
27
+ export {
28
+ initGetDefaultModelName,
29
+ initGetDefaultFieldName,
30
+ initGetModelName,
31
+ initGetFieldName,
32
+ initGetFieldAttributes,
33
+ initGetIdField,
34
+ };
35
+ export * from "./types";
36
+
37
+ let debugLogs: { instance: string; args: any[] }[] = [];
38
+ let transactionId = -1;
39
+
40
+ const createAsIsTransaction =
41
+ (adapter: DBAdapter<BetterAuthOptions>) =>
42
+ <R>(fn: (trx: DBTransactionAdapter<BetterAuthOptions>) => Promise<R>) =>
43
+ fn(adapter);
44
+
45
+ export type AdapterFactory = (
46
+ options: BetterAuthOptions,
47
+ ) => DBAdapter<BetterAuthOptions>;
48
+
49
+ export const createAdapterFactory =
50
+ ({
51
+ adapter: customAdapter,
52
+ config: cfg,
53
+ }: AdapterFactoryOptions): AdapterFactory =>
54
+ (options: BetterAuthOptions): DBAdapter<BetterAuthOptions> => {
55
+ const uniqueAdapterFactoryInstanceId = Math.random()
56
+ .toString(36)
57
+ .substring(2, 15);
58
+
59
+ const config = {
60
+ ...cfg,
61
+ supportsBooleans: cfg.supportsBooleans ?? true,
62
+ supportsDates: cfg.supportsDates ?? true,
63
+ supportsJSON: cfg.supportsJSON ?? false,
64
+ adapterName: cfg.adapterName ?? cfg.adapterId,
65
+ supportsNumericIds: cfg.supportsNumericIds ?? true,
66
+ supportsUUIDs: cfg.supportsUUIDs ?? false,
67
+ supportsArrays: cfg.supportsArrays ?? false,
68
+ transaction: cfg.transaction ?? false,
69
+ disableTransformInput: cfg.disableTransformInput ?? false,
70
+ disableTransformOutput: cfg.disableTransformOutput ?? false,
71
+ disableTransformJoin: cfg.disableTransformJoin ?? false,
72
+ } satisfies AdapterFactoryConfig;
73
+
74
+ const useNumberId =
75
+ options.advanced?.database?.useNumberId === true ||
76
+ options.advanced?.database?.generateId === "serial";
77
+ if (useNumberId && config.supportsNumericIds === false) {
78
+ throw new BetterAuthError(
79
+ `[${config.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`,
80
+ );
81
+ }
82
+
83
+ // End-user's Better-Auth instance's schema
84
+ const schema = getAuthTables(options);
85
+
86
+ const debugLog = (...args: any[]) => {
87
+ if (config.debugLogs === true || typeof config.debugLogs === "object") {
88
+ const logger = createLogger({ level: "info" });
89
+ // If we're running adapter tests, we'll keep debug logs in memory, then print them out if a test fails.
90
+ if (
91
+ typeof config.debugLogs === "object" &&
92
+ "isRunningAdapterTests" in config.debugLogs
93
+ ) {
94
+ if (config.debugLogs.isRunningAdapterTests) {
95
+ args.shift(); // Removes the {method: "..."} object from the args array.
96
+ debugLogs.push({ instance: uniqueAdapterFactoryInstanceId, args });
97
+ }
98
+ return;
99
+ }
100
+
101
+ if (
102
+ typeof config.debugLogs === "object" &&
103
+ config.debugLogs.logCondition &&
104
+ !config.debugLogs.logCondition?.()
105
+ ) {
106
+ return;
107
+ }
108
+
109
+ if (typeof args[0] === "object" && "method" in args[0]) {
110
+ const method = args.shift().method;
111
+ // Make sure the method is enabled in the config.
112
+ if (typeof config.debugLogs === "object") {
113
+ if (method === "create" && !config.debugLogs.create) {
114
+ return;
115
+ } else if (method === "update" && !config.debugLogs.update) {
116
+ return;
117
+ } else if (
118
+ method === "updateMany" &&
119
+ !config.debugLogs.updateMany
120
+ ) {
121
+ return;
122
+ } else if (method === "findOne" && !config.debugLogs.findOne) {
123
+ return;
124
+ } else if (method === "findMany" && !config.debugLogs.findMany) {
125
+ return;
126
+ } else if (method === "delete" && !config.debugLogs.delete) {
127
+ return;
128
+ } else if (
129
+ method === "deleteMany" &&
130
+ !config.debugLogs.deleteMany
131
+ ) {
132
+ return;
133
+ } else if (method === "count" && !config.debugLogs.count) {
134
+ return;
135
+ }
136
+ }
137
+ logger.info(`[${config.adapterName}]`, ...args);
138
+ } else {
139
+ logger.info(`[${config.adapterName}]`, ...args);
140
+ }
141
+ }
142
+ };
143
+
144
+ const logger = createLogger(options.logger);
145
+
146
+ const getDefaultModelName = initGetDefaultModelName({
147
+ usePlural: config.usePlural,
148
+ schema,
149
+ });
150
+
151
+ const getDefaultFieldName = initGetDefaultFieldName({
152
+ usePlural: config.usePlural,
153
+ schema,
154
+ });
155
+
156
+ const getModelName = initGetModelName({
157
+ usePlural: config.usePlural,
158
+ schema,
159
+ });
160
+ const getFieldName = initGetFieldName({
161
+ schema,
162
+ usePlural: config.usePlural,
163
+ });
164
+
165
+ const idField = initGetIdField({
166
+ schema,
167
+ options,
168
+ usePlural: config.usePlural,
169
+ disableIdGeneration: config.disableIdGeneration,
170
+ customIdGenerator: config.customIdGenerator,
171
+ supportsUUIDs: config.supportsUUIDs,
172
+ });
173
+
174
+ const getFieldAttributes = initGetFieldAttributes({
175
+ schema,
176
+ options,
177
+ usePlural: config.usePlural,
178
+ disableIdGeneration: config.disableIdGeneration,
179
+ customIdGenerator: config.customIdGenerator,
180
+ });
181
+
182
+ const transformInput = async (
183
+ data: Record<string, any>,
184
+ defaultModelName: string,
185
+ action: "create" | "update" | "findOne" | "findMany",
186
+ forceAllowId?: boolean,
187
+ ) => {
188
+ const transformedData: Record<string, any> = {};
189
+ const fields = schema[defaultModelName]!.fields;
190
+
191
+ const newMappedKeys = config.mapKeysTransformInput ?? {};
192
+ const useNumberId =
193
+ options.advanced?.database?.useNumberId ||
194
+ options.advanced?.database?.generateId === "serial";
195
+ fields.id = idField({
196
+ customModelName: defaultModelName,
197
+ forceAllowId: forceAllowId && "id" in data,
198
+ });
199
+ for (const field in fields) {
200
+ let value = data[field];
201
+ const fieldAttributes = fields[field];
202
+
203
+ const newFieldName: string =
204
+ newMappedKeys[field] || fields[field]!.fieldName || field;
205
+ if (
206
+ value === undefined &&
207
+ ((fieldAttributes!.defaultValue === undefined &&
208
+ !fieldAttributes!.transform?.input &&
209
+ !(action === "update" && fieldAttributes!.onUpdate)) ||
210
+ (action === "update" && !fieldAttributes!.onUpdate))
211
+ ) {
212
+ continue;
213
+ }
214
+
215
+ // In some endpoints (like signUpEmail) where there isn't proper Zod validation,
216
+ // we might receive a date as a string (this is because of the client converting the Date to a string
217
+ // when sending to the server). Because of this, we'll convert the string to a Date.
218
+ if (
219
+ fieldAttributes &&
220
+ fieldAttributes.type === "date" &&
221
+ !(value instanceof Date) &&
222
+ typeof value === "string"
223
+ ) {
224
+ try {
225
+ value = new Date(value);
226
+ } catch {
227
+ logger.error("[Adapter Factory] Failed to convert string to date", {
228
+ value,
229
+ field,
230
+ });
231
+ }
232
+ }
233
+
234
+ // If the value is undefined, but the fieldAttr provides a `defaultValue`, then we'll use that.
235
+ let newValue = withApplyDefault(value, fieldAttributes!, action);
236
+
237
+ // If the field attr provides a custom transform input, then we'll let it handle the value transformation.
238
+ // Afterwards, we'll continue to apply the default transformations just to make sure it saves in the correct format.
239
+ if (fieldAttributes!.transform?.input) {
240
+ newValue = await fieldAttributes!.transform.input(newValue);
241
+ }
242
+
243
+ if (fieldAttributes!.references?.field === "id" && useNumberId) {
244
+ if (Array.isArray(newValue)) {
245
+ newValue = newValue.map((x) => (x !== null ? Number(x) : null));
246
+ } else {
247
+ newValue = newValue !== null ? Number(newValue) : null;
248
+ }
249
+ } else if (
250
+ config.supportsJSON === false &&
251
+ typeof newValue === "object" &&
252
+ fieldAttributes!.type === "json"
253
+ ) {
254
+ newValue = JSON.stringify(newValue);
255
+ } else if (
256
+ config.supportsArrays === false &&
257
+ Array.isArray(newValue) &&
258
+ (fieldAttributes!.type === "string[]" ||
259
+ fieldAttributes!.type === "number[]")
260
+ ) {
261
+ newValue = JSON.stringify(newValue);
262
+ } else if (
263
+ config.supportsDates === false &&
264
+ newValue instanceof Date &&
265
+ fieldAttributes!.type === "date"
266
+ ) {
267
+ newValue = newValue.toISOString();
268
+ } else if (
269
+ config.supportsBooleans === false &&
270
+ typeof newValue === "boolean"
271
+ ) {
272
+ newValue = newValue ? 1 : 0;
273
+ }
274
+
275
+ if (config.customTransformInput) {
276
+ newValue = config.customTransformInput({
277
+ data: newValue,
278
+ action,
279
+ field: newFieldName,
280
+ fieldAttributes: fieldAttributes!,
281
+ model: getModelName(defaultModelName),
282
+ schema,
283
+ options,
284
+ });
285
+ }
286
+
287
+ if (newValue !== undefined) {
288
+ transformedData[newFieldName] = newValue;
289
+ }
290
+ }
291
+ return transformedData;
292
+ };
293
+
294
+ const transformOutput = async (
295
+ data: Record<string, any> | null,
296
+ unsafe_model: string,
297
+ select: string[] = [],
298
+ join: JoinConfig | undefined,
299
+ ) => {
300
+ const transformSingleOutput = async (
301
+ data: Record<string, any> | null,
302
+ unsafe_model: string,
303
+ select: string[] = [],
304
+ ) => {
305
+ if (!data) return null;
306
+ const newMappedKeys = config.mapKeysTransformOutput ?? {};
307
+ const transformedData: Record<string, any> = {};
308
+ const tableSchema = schema[getDefaultModelName(unsafe_model)]!.fields;
309
+ const idKey = Object.entries(newMappedKeys).find(
310
+ ([_, v]) => v === "id",
311
+ )?.[0];
312
+ const useNumberId =
313
+ options.advanced?.database?.useNumberId ||
314
+ options.advanced?.database?.generateId === "serial";
315
+ tableSchema[idKey ?? "id"] = {
316
+ type: useNumberId ? "number" : "string",
317
+ };
318
+ for (const key in tableSchema) {
319
+ if (select.length && !select.includes(key)) {
320
+ continue;
321
+ }
322
+ const field = tableSchema[key];
323
+ if (field) {
324
+ const originalKey = field.fieldName || key;
325
+
326
+ // If the field is mapped, we'll use the mapped key. Otherwise, we'll use the original key.
327
+ let newValue =
328
+ data[
329
+ Object.entries(newMappedKeys).find(
330
+ ([_, v]) => v === originalKey,
331
+ )?.[0] || originalKey
332
+ ];
333
+
334
+ if (field.transform?.output) {
335
+ newValue = await field.transform.output(newValue);
336
+ }
337
+
338
+ const newFieldName: string = newMappedKeys[key] || key;
339
+
340
+ if (originalKey === "id" || field.references?.field === "id") {
341
+ // Even if `useNumberId` is true, we must always return a string `id` output.
342
+ if (typeof newValue !== "undefined" && newValue !== null)
343
+ newValue = String(newValue);
344
+ } else if (
345
+ config.supportsJSON === false &&
346
+ typeof newValue === "string" &&
347
+ field.type === "json"
348
+ ) {
349
+ newValue = safeJSONParse(newValue);
350
+ } else if (
351
+ config.supportsArrays === false &&
352
+ typeof newValue === "string" &&
353
+ (field.type === "string[]" || field.type === "number[]")
354
+ ) {
355
+ newValue = safeJSONParse(newValue);
356
+ } else if (
357
+ config.supportsDates === false &&
358
+ typeof newValue === "string" &&
359
+ field.type === "date"
360
+ ) {
361
+ newValue = new Date(newValue);
362
+ } else if (
363
+ config.supportsBooleans === false &&
364
+ typeof newValue === "number" &&
365
+ field.type === "boolean"
366
+ ) {
367
+ newValue = newValue === 1;
368
+ }
369
+
370
+ if (config.customTransformOutput) {
371
+ newValue = config.customTransformOutput({
372
+ data: newValue,
373
+ field: newFieldName,
374
+ fieldAttributes: field,
375
+ select,
376
+ model: getModelName(unsafe_model),
377
+ schema,
378
+ options,
379
+ });
380
+ }
381
+
382
+ transformedData[newFieldName] = newValue;
383
+ }
384
+ }
385
+ return transformedData as any;
386
+ };
387
+
388
+ if (!join || Object.keys(join).length === 0) {
389
+ return await transformSingleOutput(data, unsafe_model, select);
390
+ }
391
+
392
+ unsafe_model = getDefaultModelName(unsafe_model);
393
+ // for now we just transform the base model
394
+ // later we append the joined models to this object.
395
+ const transformedData: Record<string, any> = await transformSingleOutput(
396
+ data,
397
+ unsafe_model,
398
+ select,
399
+ );
400
+
401
+ // Get all the models that are required to be joined.
402
+ const requiredModels = Object.entries(join).map(
403
+ ([model, joinConfig]) => ({
404
+ modelName: getModelName(model),
405
+ defaultModelName: getDefaultModelName(model),
406
+ joinConfig,
407
+ }),
408
+ );
409
+
410
+ if (!data) return null;
411
+ // Data is now the base model object directly (not wrapped under a key)
412
+
413
+ for (const {
414
+ modelName,
415
+ defaultModelName,
416
+ joinConfig,
417
+ } of requiredModels) {
418
+ let joinedData = await (async () => {
419
+ if (options.experimental?.joins) {
420
+ const result = data[modelName];
421
+ return result;
422
+ } else {
423
+ // doesn't support joins, so fallback to handleFallbackJoin
424
+ const result = await handleFallbackJoin({
425
+ baseModel: unsafe_model,
426
+ baseData: transformedData,
427
+ joinModel: modelName,
428
+ specificJoinConfig: joinConfig,
429
+ });
430
+ return result;
431
+ }
432
+ })();
433
+
434
+ // If joinedData is undefined, initialize it based on relationship type
435
+ if (joinedData === undefined || joinedData === null) {
436
+ joinedData = joinConfig.relation === "one-to-one" ? null : [];
437
+ }
438
+
439
+ if (
440
+ joinConfig.relation === "one-to-many" &&
441
+ !Array.isArray(joinedData)
442
+ ) {
443
+ joinedData = [joinedData];
444
+ }
445
+
446
+ const transformed = [];
447
+
448
+ if (Array.isArray(joinedData)) {
449
+ for (const item of joinedData) {
450
+ const transformedItem = await transformSingleOutput(
451
+ item,
452
+ modelName,
453
+ [],
454
+ );
455
+ transformed.push(transformedItem);
456
+ }
457
+ } else {
458
+ const transformedItem = await transformSingleOutput(
459
+ joinedData,
460
+ modelName,
461
+ [],
462
+ );
463
+ transformed.push(transformedItem);
464
+ }
465
+
466
+ const result =
467
+ joinConfig.relation === "one-to-one" ? transformed[0] : transformed;
468
+ transformedData[defaultModelName] = result ?? null;
469
+ }
470
+
471
+ return transformedData as any;
472
+ };
473
+
474
+ const transformWhereClause = <W extends Where[] | undefined>({
475
+ model,
476
+ where,
477
+ action,
478
+ }: {
479
+ where: W;
480
+ model: string;
481
+ action:
482
+ | "create"
483
+ | "update"
484
+ | "findOne"
485
+ | "findMany"
486
+ | "updateMany"
487
+ | "delete"
488
+ | "deleteMany"
489
+ | "count";
490
+ }): W extends undefined ? undefined : CleanedWhere[] => {
491
+ if (!where) return undefined as any;
492
+ const newMappedKeys = config.mapKeysTransformInput ?? {};
493
+
494
+ return where.map((w) => {
495
+ const {
496
+ field: unsafe_field,
497
+ value,
498
+ operator = "eq",
499
+ connector = "AND",
500
+ } = w;
501
+ if (operator === "in") {
502
+ if (!Array.isArray(value)) {
503
+ throw new BetterAuthError("Value must be an array");
504
+ }
505
+ }
506
+
507
+ let newValue = value;
508
+
509
+ const defaultModelName = getDefaultModelName(model);
510
+ const defaultFieldName = getDefaultFieldName({
511
+ field: unsafe_field,
512
+ model,
513
+ });
514
+ const fieldName: string =
515
+ newMappedKeys[defaultFieldName] ||
516
+ getFieldName({
517
+ field: defaultFieldName,
518
+ model: defaultModelName,
519
+ });
520
+
521
+ const fieldAttr = getFieldAttributes({
522
+ field: defaultFieldName,
523
+ model: defaultModelName,
524
+ });
525
+
526
+ const useNumberId =
527
+ options.advanced?.database?.useNumberId ||
528
+ options.advanced?.database?.generateId === "serial";
529
+
530
+ if (
531
+ defaultFieldName === "id" ||
532
+ fieldAttr!.references?.field === "id"
533
+ ) {
534
+ if (useNumberId) {
535
+ if (Array.isArray(value)) {
536
+ newValue = value.map(Number);
537
+ } else {
538
+ newValue = Number(value);
539
+ }
540
+ }
541
+ }
542
+
543
+ if (
544
+ fieldAttr.type === "date" &&
545
+ value instanceof Date &&
546
+ !config.supportsDates
547
+ ) {
548
+ newValue = value.toISOString();
549
+ }
550
+
551
+ if (
552
+ fieldAttr.type === "boolean" &&
553
+ typeof value === "boolean" &&
554
+ !config.supportsBooleans
555
+ ) {
556
+ newValue = value ? 1 : 0;
557
+ }
558
+
559
+ if (
560
+ fieldAttr.type === "json" &&
561
+ typeof value === "object" &&
562
+ !config.supportsJSON
563
+ ) {
564
+ try {
565
+ const stringifiedJSON = JSON.stringify(value);
566
+ newValue = stringifiedJSON;
567
+ } catch (error) {
568
+ throw new Error(
569
+ `Failed to stringify JSON value for field ${fieldName}`,
570
+ { cause: error },
571
+ );
572
+ }
573
+ }
574
+
575
+ if (config.customTransformInput) {
576
+ newValue = config.customTransformInput({
577
+ data: newValue,
578
+ fieldAttributes: fieldAttr,
579
+ field: fieldName,
580
+ model: getModelName(model),
581
+ schema,
582
+ options,
583
+ action,
584
+ });
585
+ }
586
+
587
+ return {
588
+ operator,
589
+ connector,
590
+ field: fieldName,
591
+ value: newValue,
592
+ } satisfies CleanedWhere;
593
+ }) as any;
594
+ };
595
+
596
+ const transformJoinClause = (
597
+ baseModel: string,
598
+ unsanitizedJoin: JoinOption | undefined,
599
+ select: string[] | undefined,
600
+ ): { join: JoinConfig; select: string[] | undefined } | undefined => {
601
+ if (!unsanitizedJoin) return undefined;
602
+ if (Object.keys(unsanitizedJoin).length === 0) return undefined;
603
+ const transformedJoin: JoinConfig = {};
604
+ for (const [model, join] of Object.entries(unsanitizedJoin)) {
605
+ if (!join) continue;
606
+ const defaultModelName = getDefaultModelName(model);
607
+ const defaultBaseModelName = getDefaultModelName(baseModel);
608
+
609
+ // First, check if the joined model has FKs to the base model (forward join)
610
+ let foreignKeys = Object.entries(
611
+ schema[defaultModelName]!.fields,
612
+ ).filter(
613
+ ([field, fieldAttributes]) =>
614
+ fieldAttributes.references &&
615
+ getDefaultModelName(fieldAttributes.references.model) ===
616
+ defaultBaseModelName,
617
+ );
618
+
619
+ let isForwardJoin = true;
620
+
621
+ // If no forward join found, check backwards: does the base model have FKs to the joined model?
622
+ if (!foreignKeys.length) {
623
+ foreignKeys = Object.entries(
624
+ schema[defaultBaseModelName]!.fields,
625
+ ).filter(
626
+ ([field, fieldAttributes]) =>
627
+ fieldAttributes.references &&
628
+ getDefaultModelName(fieldAttributes.references.model) ===
629
+ defaultModelName,
630
+ );
631
+ isForwardJoin = false;
632
+ }
633
+
634
+ if (!foreignKeys.length) {
635
+ throw new BetterAuthError(
636
+ `No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`,
637
+ );
638
+ } else if (foreignKeys.length > 1) {
639
+ throw new BetterAuthError(
640
+ `Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`,
641
+ );
642
+ }
643
+
644
+ const [foreignKey, foreignKeyAttributes] = foreignKeys[0]!;
645
+ if (!foreignKeyAttributes.references) {
646
+ // this should never happen, as we filter for references in the foreign keys.
647
+ // it's here for typescript to be happy.
648
+ throw new BetterAuthError(
649
+ `No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`,
650
+ );
651
+ }
652
+
653
+ let from: string;
654
+ let to: string;
655
+ let requiredSelectField: string;
656
+
657
+ if (isForwardJoin) {
658
+ // joined model has FK to base model
659
+ // The field we need in select is the referenced field in the base model
660
+ requiredSelectField = foreignKeyAttributes.references.field;
661
+ from = getFieldName({
662
+ model: baseModel,
663
+ field: requiredSelectField,
664
+ });
665
+
666
+ to = getFieldName({
667
+ model,
668
+ field: foreignKey,
669
+ });
670
+ } else {
671
+ // base model has FK to joined model
672
+ // The field we need in select is the foreign key field in the base model
673
+ requiredSelectField = foreignKey;
674
+ from = getFieldName({
675
+ model: baseModel,
676
+ field: requiredSelectField,
677
+ });
678
+
679
+ to = getFieldName({
680
+ model,
681
+ field: foreignKeyAttributes.references.field,
682
+ });
683
+ }
684
+
685
+ // Ensure the required field is in select if select is provided
686
+ if (select && !select.includes(requiredSelectField)) {
687
+ select.push(requiredSelectField);
688
+ }
689
+
690
+ const isUnique =
691
+ to === "id" ? true : (foreignKeyAttributes.unique ?? false);
692
+
693
+ let limit: number =
694
+ options.advanced?.database?.defaultFindManyLimit ?? 100;
695
+ if (isUnique) {
696
+ limit = 1;
697
+ } else if (typeof join === "object" && typeof join.limit === "number") {
698
+ limit = join.limit;
699
+ }
700
+
701
+ transformedJoin[getModelName(model)] = {
702
+ on: {
703
+ from,
704
+ to,
705
+ },
706
+ limit,
707
+ relation: isUnique ? "one-to-one" : "one-to-many",
708
+ };
709
+ }
710
+ return { join: transformedJoin, select };
711
+ };
712
+
713
+ /**
714
+ * Handle joins by making separate queries and combining results (fallback for adapters that don't support native joins).
715
+ */
716
+ const handleFallbackJoin = async <T extends Record<string, any> | null>({
717
+ baseModel,
718
+ baseData,
719
+ joinModel,
720
+ specificJoinConfig: joinConfig,
721
+ }: {
722
+ baseModel: string;
723
+ baseData: T;
724
+ joinModel: string;
725
+ specificJoinConfig: JoinConfig[number];
726
+ }) => {
727
+ if (!baseData) return baseData;
728
+ const modelName = getModelName(joinModel);
729
+ const field = joinConfig.on.to;
730
+ const value =
731
+ baseData[
732
+ getDefaultFieldName({ field: joinConfig.on.from, model: baseModel })
733
+ ];
734
+
735
+ if (value === null || value === undefined) {
736
+ // If there is no value, it could mean that the query used a `select` clause that didn't include the field.
737
+ // or the query result is purely empty.
738
+ // In any case, we return null/empty array.
739
+ return joinConfig.relation === "one-to-one" ? null : [];
740
+ }
741
+ let result: Record<string, any> | Record<string, any>[] | null;
742
+ const where = transformWhereClause({
743
+ model: modelName,
744
+ where: [
745
+ {
746
+ field,
747
+ value,
748
+ operator: "eq",
749
+ connector: "AND",
750
+ },
751
+ ],
752
+ action: "findOne",
753
+ });
754
+ try {
755
+ if (joinConfig.relation === "one-to-one") {
756
+ result = await adapterInstance.findOne<Record<string, any>>({
757
+ model: modelName,
758
+ where: where,
759
+ });
760
+ } else {
761
+ const limit =
762
+ joinConfig.limit ??
763
+ options.advanced?.database?.defaultFindManyLimit ??
764
+ 100;
765
+ result = await adapterInstance.findMany<Record<string, any>>({
766
+ model: modelName,
767
+ where: where,
768
+ limit,
769
+ });
770
+ }
771
+ } catch (error) {
772
+ logger.error(`Failed to query fallback join for model ${modelName}:`, {
773
+ where,
774
+ limit: joinConfig.limit,
775
+ });
776
+ console.error(error);
777
+ throw error;
778
+ }
779
+ return result;
780
+ };
781
+
782
+ const adapterInstance = customAdapter({
783
+ options,
784
+ schema,
785
+ debugLog,
786
+ getFieldName,
787
+ getModelName,
788
+ getDefaultModelName,
789
+ getDefaultFieldName,
790
+ getFieldAttributes,
791
+ transformInput,
792
+ transformOutput,
793
+ transformWhereClause,
794
+ });
795
+
796
+ let lazyLoadTransaction:
797
+ | DBAdapter<BetterAuthOptions>["transaction"]
798
+ | null = null;
799
+ const adapter: DBAdapter<BetterAuthOptions> = {
800
+ transaction: async (cb) => {
801
+ if (!lazyLoadTransaction) {
802
+ if (!config.transaction) {
803
+ lazyLoadTransaction = createAsIsTransaction(adapter);
804
+ } else {
805
+ logger.debug(
806
+ `[${config.adapterName}] - Using provided transaction implementation.`,
807
+ );
808
+ lazyLoadTransaction = config.transaction;
809
+ }
810
+ }
811
+ return lazyLoadTransaction(cb);
812
+ },
813
+ create: async <T extends Record<string, any>, R = T>({
814
+ data: unsafeData,
815
+ model: unsafeModel,
816
+ select,
817
+ forceAllowId = false,
818
+ }: {
819
+ model: string;
820
+ data: T;
821
+ select?: string[];
822
+ forceAllowId?: boolean;
823
+ }): Promise<R> => {
824
+ transactionId++;
825
+ const thisTransactionId = transactionId;
826
+ const model = getModelName(unsafeModel);
827
+ unsafeModel = getDefaultModelName(unsafeModel);
828
+ if (
829
+ "id" in unsafeData &&
830
+ typeof unsafeData.id !== "undefined" &&
831
+ !forceAllowId
832
+ ) {
833
+ // The reason why `forceAllowId` was introduced was because we used to handle
834
+ // id generation ourselves (eg adapter.create({ data: { id: "123" } }))
835
+ // This was bad as certain things (such as number ids) would not work as expected.
836
+ // Since then, we have introduced the `forceAllowId` parameter to allow users to
837
+ // bypass this check. Otherwise, we would throw a warning stating that the id will be ignored
838
+ logger.warn(
839
+ `[${config.adapterName}] - You are trying to create a record with an id. This is not allowed as we handle id generation for you, unless you pass in the \`forceAllowId\` parameter. The id will be ignored.`,
840
+ );
841
+ const err = new Error();
842
+ const stack = err.stack
843
+ ?.split("\n")
844
+ .filter((_, i) => i !== 1)
845
+ .join("\n")
846
+ .replace("Error:", "Create method with `id` being called at:");
847
+ console.log(stack);
848
+ //@ts-expect-error
849
+ unsafeData.id = undefined;
850
+ }
851
+ debugLog(
852
+ { method: "create" },
853
+ `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`,
854
+ `${formatMethod("create")} ${formatAction("Unsafe Input")}:`,
855
+ { model, data: unsafeData },
856
+ );
857
+ let data = unsafeData;
858
+ if (!config.disableTransformInput) {
859
+ data = (await transformInput(
860
+ unsafeData,
861
+ unsafeModel,
862
+ "create",
863
+ forceAllowId,
864
+ )) as T;
865
+ }
866
+ debugLog(
867
+ { method: "create" },
868
+ `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`,
869
+ `${formatMethod("create")} ${formatAction("Parsed Input")}:`,
870
+ { model, data },
871
+ );
872
+ const res = await adapterInstance.create<T>({ data, model });
873
+ debugLog(
874
+ { method: "create" },
875
+ `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`,
876
+ `${formatMethod("create")} ${formatAction("DB Result")}:`,
877
+ { model, res },
878
+ );
879
+ let transformed = res as any;
880
+ if (!config.disableTransformOutput) {
881
+ transformed = await transformOutput(
882
+ res as any,
883
+ unsafeModel,
884
+ select,
885
+ undefined,
886
+ );
887
+ }
888
+ debugLog(
889
+ { method: "create" },
890
+ `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`,
891
+ `${formatMethod("create")} ${formatAction("Parsed Result")}:`,
892
+ { model, data: transformed },
893
+ );
894
+ return transformed;
895
+ },
896
+ update: async <T>({
897
+ model: unsafeModel,
898
+ where: unsafeWhere,
899
+ update: unsafeData,
900
+ }: {
901
+ model: string;
902
+ where: Where[];
903
+ update: Record<string, any>;
904
+ }): Promise<T | null> => {
905
+ transactionId++;
906
+ const thisTransactionId = transactionId;
907
+ unsafeModel = getDefaultModelName(unsafeModel);
908
+ const model = getModelName(unsafeModel);
909
+ const where = transformWhereClause({
910
+ model: unsafeModel,
911
+ where: unsafeWhere,
912
+ action: "update",
913
+ });
914
+ debugLog(
915
+ { method: "update" },
916
+ `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`,
917
+ `${formatMethod("update")} ${formatAction("Unsafe Input")}:`,
918
+ { model, data: unsafeData },
919
+ );
920
+ let data = unsafeData as T;
921
+ if (!config.disableTransformInput) {
922
+ data = (await transformInput(unsafeData, unsafeModel, "update")) as T;
923
+ }
924
+ debugLog(
925
+ { method: "update" },
926
+ `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`,
927
+ `${formatMethod("update")} ${formatAction("Parsed Input")}:`,
928
+ { model, data },
929
+ );
930
+ const res = await adapterInstance.update<T>({
931
+ model,
932
+ where,
933
+ update: data,
934
+ });
935
+ debugLog(
936
+ { method: "update" },
937
+ `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`,
938
+ `${formatMethod("update")} ${formatAction("DB Result")}:`,
939
+ { model, data: res },
940
+ );
941
+ let transformed = res as any;
942
+ if (!config.disableTransformOutput) {
943
+ transformed = await transformOutput(
944
+ res as any,
945
+ unsafeModel,
946
+ undefined,
947
+ undefined,
948
+ );
949
+ }
950
+ debugLog(
951
+ { method: "update" },
952
+ `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`,
953
+ `${formatMethod("update")} ${formatAction("Parsed Result")}:`,
954
+ { model, data: transformed },
955
+ );
956
+ return transformed;
957
+ },
958
+ updateMany: async ({
959
+ model: unsafeModel,
960
+ where: unsafeWhere,
961
+ update: unsafeData,
962
+ }: {
963
+ model: string;
964
+ where: Where[];
965
+ update: Record<string, any>;
966
+ }) => {
967
+ transactionId++;
968
+ const thisTransactionId = transactionId;
969
+ const model = getModelName(unsafeModel);
970
+ const where = transformWhereClause({
971
+ model: unsafeModel,
972
+ where: unsafeWhere,
973
+ action: "updateMany",
974
+ });
975
+ unsafeModel = getDefaultModelName(unsafeModel);
976
+ debugLog(
977
+ { method: "updateMany" },
978
+ `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`,
979
+ `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`,
980
+ { model, data: unsafeData },
981
+ );
982
+ let data = unsafeData;
983
+ if (!config.disableTransformInput) {
984
+ data = await transformInput(unsafeData, unsafeModel, "update");
985
+ }
986
+ debugLog(
987
+ { method: "updateMany" },
988
+ `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`,
989
+ `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`,
990
+ { model, data },
991
+ );
992
+
993
+ const updatedCount = await adapterInstance.updateMany({
994
+ model,
995
+ where,
996
+ update: data,
997
+ });
998
+ debugLog(
999
+ { method: "updateMany" },
1000
+ `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`,
1001
+ `${formatMethod("updateMany")} ${formatAction("DB Result")}:`,
1002
+ { model, data: updatedCount },
1003
+ );
1004
+ debugLog(
1005
+ { method: "updateMany" },
1006
+ `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`,
1007
+ `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`,
1008
+ { model, data: updatedCount },
1009
+ );
1010
+ return updatedCount;
1011
+ },
1012
+ findOne: async <T extends Record<string, any>>({
1013
+ model: unsafeModel,
1014
+ where: unsafeWhere,
1015
+ select,
1016
+ join: unsafeJoin,
1017
+ }: {
1018
+ model: string;
1019
+ where: Where[];
1020
+ select?: string[];
1021
+ join?: JoinOption;
1022
+ }) => {
1023
+ transactionId++;
1024
+ const thisTransactionId = transactionId;
1025
+ const model = getModelName(unsafeModel);
1026
+ const where = transformWhereClause({
1027
+ model: unsafeModel,
1028
+ where: unsafeWhere,
1029
+ action: "findOne",
1030
+ });
1031
+ unsafeModel = getDefaultModelName(unsafeModel);
1032
+ let join: JoinConfig | undefined;
1033
+ let passJoinToAdapter = true;
1034
+ if (!config.disableTransformJoin) {
1035
+ const result = transformJoinClause(unsafeModel, unsafeJoin, select);
1036
+ if (result) {
1037
+ join = result.join;
1038
+ select = result.select;
1039
+ }
1040
+ // If adapter doesn't support joins and we have joins, don't pass them to the adapter
1041
+ const experimentalJoins = options.experimental?.joins;
1042
+ if (!experimentalJoins && join && Object.keys(join).length > 0) {
1043
+ passJoinToAdapter = false;
1044
+ }
1045
+ } else {
1046
+ // assume it's already transformed if transformation is disabled
1047
+ join = unsafeJoin as never as JoinConfig;
1048
+ }
1049
+ debugLog(
1050
+ { method: "findOne" },
1051
+ `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`,
1052
+ `${formatMethod("findOne")}:`,
1053
+ { model, where, select, join },
1054
+ );
1055
+
1056
+ const res = await adapterInstance.findOne<T>({
1057
+ model,
1058
+ where,
1059
+ select,
1060
+ join: passJoinToAdapter ? join : undefined,
1061
+ });
1062
+ debugLog(
1063
+ { method: "findOne" },
1064
+ `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`,
1065
+ `${formatMethod("findOne")} ${formatAction("DB Result")}:`,
1066
+ { model, data: res },
1067
+ );
1068
+
1069
+ // Handle fallback join if adapter doesn't support joins
1070
+ let transformed = res as any;
1071
+ if (!config.disableTransformOutput) {
1072
+ transformed = await transformOutput(res, unsafeModel, select, join);
1073
+ }
1074
+ debugLog(
1075
+ { method: "findOne" },
1076
+ `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`,
1077
+ `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`,
1078
+ { model, data: transformed },
1079
+ );
1080
+ return transformed;
1081
+ },
1082
+ findMany: async <T extends Record<string, any>>({
1083
+ model: unsafeModel,
1084
+ where: unsafeWhere,
1085
+ limit: unsafeLimit,
1086
+ sortBy,
1087
+ offset,
1088
+ join: unsafeJoin,
1089
+ }: {
1090
+ model: string;
1091
+ where?: Where[];
1092
+ limit?: number;
1093
+ sortBy?: { field: string; direction: "asc" | "desc" };
1094
+ offset?: number;
1095
+ join?: JoinOption;
1096
+ }) => {
1097
+ transactionId++;
1098
+ const thisTransactionId = transactionId;
1099
+ const limit =
1100
+ unsafeLimit ??
1101
+ options.advanced?.database?.defaultFindManyLimit ??
1102
+ 100;
1103
+ const model = getModelName(unsafeModel);
1104
+ const where = transformWhereClause({
1105
+ model: unsafeModel,
1106
+ where: unsafeWhere,
1107
+ action: "findMany",
1108
+ });
1109
+ unsafeModel = getDefaultModelName(unsafeModel);
1110
+ let join: JoinConfig | undefined;
1111
+ let passJoinToAdapter = true;
1112
+ if (!config.disableTransformJoin) {
1113
+ const result = transformJoinClause(
1114
+ unsafeModel,
1115
+ unsafeJoin,
1116
+ undefined,
1117
+ );
1118
+ if (result) {
1119
+ join = result.join;
1120
+ }
1121
+ // If adapter doesn't support joins and we have joins, don't pass them to the adapter
1122
+ const experimentalJoins = options.experimental?.joins;
1123
+ if (!experimentalJoins && join && Object.keys(join).length > 0) {
1124
+ passJoinToAdapter = false;
1125
+ }
1126
+ } else {
1127
+ // assume it's already transformed if transformation is disabled
1128
+ join = unsafeJoin as never as JoinConfig;
1129
+ }
1130
+ debugLog(
1131
+ { method: "findMany" },
1132
+ `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`,
1133
+ `${formatMethod("findMany")}:`,
1134
+ { model, where, limit, sortBy, offset, join },
1135
+ );
1136
+ const res = await adapterInstance.findMany<T>({
1137
+ model,
1138
+ where,
1139
+ limit: limit,
1140
+ sortBy,
1141
+ offset,
1142
+ join: passJoinToAdapter ? join : undefined,
1143
+ });
1144
+ debugLog(
1145
+ { method: "findMany" },
1146
+ `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`,
1147
+ `${formatMethod("findMany")} ${formatAction("DB Result")}:`,
1148
+ { model, data: res },
1149
+ );
1150
+
1151
+ let transformed = res as any;
1152
+ if (!config.disableTransformOutput) {
1153
+ transformed = await Promise.all(
1154
+ res.map(async (r: Record<string, any>) => {
1155
+ return await transformOutput(r, unsafeModel, undefined, join);
1156
+ }),
1157
+ );
1158
+ }
1159
+
1160
+ debugLog(
1161
+ { method: "findMany" },
1162
+ `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`,
1163
+ `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`,
1164
+ { model, data: transformed },
1165
+ );
1166
+ return transformed;
1167
+ },
1168
+ delete: async ({
1169
+ model: unsafeModel,
1170
+ where: unsafeWhere,
1171
+ }: {
1172
+ model: string;
1173
+ where: Where[];
1174
+ }) => {
1175
+ transactionId++;
1176
+ const thisTransactionId = transactionId;
1177
+ const model = getModelName(unsafeModel);
1178
+ const where = transformWhereClause({
1179
+ model: unsafeModel,
1180
+ where: unsafeWhere,
1181
+ action: "delete",
1182
+ });
1183
+ unsafeModel = getDefaultModelName(unsafeModel);
1184
+ debugLog(
1185
+ { method: "delete" },
1186
+ `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`,
1187
+ `${formatMethod("delete")}:`,
1188
+ { model, where },
1189
+ );
1190
+ await adapterInstance.delete({
1191
+ model,
1192
+ where,
1193
+ });
1194
+ debugLog(
1195
+ { method: "delete" },
1196
+ `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`,
1197
+ `${formatMethod("delete")} ${formatAction("DB Result")}:`,
1198
+ { model },
1199
+ );
1200
+ },
1201
+ deleteMany: async ({
1202
+ model: unsafeModel,
1203
+ where: unsafeWhere,
1204
+ }: {
1205
+ model: string;
1206
+ where: Where[];
1207
+ }) => {
1208
+ transactionId++;
1209
+ const thisTransactionId = transactionId;
1210
+ const model = getModelName(unsafeModel);
1211
+ const where = transformWhereClause({
1212
+ model: unsafeModel,
1213
+ where: unsafeWhere,
1214
+ action: "deleteMany",
1215
+ });
1216
+ unsafeModel = getDefaultModelName(unsafeModel);
1217
+ debugLog(
1218
+ { method: "deleteMany" },
1219
+ `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`,
1220
+ `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`,
1221
+ { model, where },
1222
+ );
1223
+ const res = await adapterInstance.deleteMany({
1224
+ model,
1225
+ where,
1226
+ });
1227
+ debugLog(
1228
+ { method: "deleteMany" },
1229
+ `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`,
1230
+ `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`,
1231
+ { model, data: res },
1232
+ );
1233
+ return res;
1234
+ },
1235
+ count: async ({
1236
+ model: unsafeModel,
1237
+ where: unsafeWhere,
1238
+ }: {
1239
+ model: string;
1240
+ where?: Where[];
1241
+ }) => {
1242
+ transactionId++;
1243
+ const thisTransactionId = transactionId;
1244
+ const model = getModelName(unsafeModel);
1245
+ const where = transformWhereClause({
1246
+ model: unsafeModel,
1247
+ where: unsafeWhere,
1248
+ action: "count",
1249
+ });
1250
+ unsafeModel = getDefaultModelName(unsafeModel);
1251
+ debugLog(
1252
+ { method: "count" },
1253
+ `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`,
1254
+ `${formatMethod("count")}:`,
1255
+ {
1256
+ model,
1257
+ where,
1258
+ },
1259
+ );
1260
+ const res = await adapterInstance.count({
1261
+ model,
1262
+ where,
1263
+ });
1264
+ debugLog(
1265
+ { method: "count" },
1266
+ `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`,
1267
+ `${formatMethod("count")}:`,
1268
+ {
1269
+ model,
1270
+ data: res,
1271
+ },
1272
+ );
1273
+ return res;
1274
+ },
1275
+ createSchema: adapterInstance.createSchema
1276
+ ? async (_, file) => {
1277
+ const tables = getAuthTables(options);
1278
+
1279
+ if (
1280
+ options.secondaryStorage &&
1281
+ !options.session?.storeSessionInDatabase
1282
+ ) {
1283
+ // biome-ignore lint/performance/noDelete: If the user has enabled secondaryStorage, as well as not specifying to store session table in DB, then createSchema shouldn't generate schema table.
1284
+ delete tables.session;
1285
+ }
1286
+
1287
+ return adapterInstance.createSchema!({ file, tables });
1288
+ }
1289
+ : undefined,
1290
+ options: {
1291
+ adapterConfig: config,
1292
+ ...(adapterInstance.options ?? {}),
1293
+ },
1294
+ id: config.adapterId,
1295
+
1296
+ // Secretly export values ONLY if this adapter has enabled adapter-test-debug-logs.
1297
+ // This would then be used during our adapter-tests to help print debug logs if a test fails.
1298
+ //@ts-expect-error - ^^
1299
+ ...(config.debugLogs?.isRunningAdapterTests
1300
+ ? {
1301
+ adapterTestDebugLogs: {
1302
+ resetDebugLogs() {
1303
+ debugLogs = debugLogs.filter(
1304
+ (log) => log.instance !== uniqueAdapterFactoryInstanceId,
1305
+ );
1306
+ },
1307
+ printDebugLogs() {
1308
+ const separator = `─`.repeat(80);
1309
+ const logs = debugLogs.filter(
1310
+ (log) => log.instance === uniqueAdapterFactoryInstanceId,
1311
+ );
1312
+ if (logs.length === 0) {
1313
+ return;
1314
+ }
1315
+
1316
+ //`${colors.fg.blue}|${colors.reset} `,
1317
+ const log: any[] = logs
1318
+ .reverse()
1319
+ .map((log) => {
1320
+ log.args[0] = `\n${log.args[0]}`;
1321
+ return [...log.args, "\n"];
1322
+ })
1323
+ .reduce(
1324
+ (prev, curr) => {
1325
+ return [...curr, ...prev];
1326
+ },
1327
+ [`\n${separator}`],
1328
+ );
1329
+
1330
+ console.log(...log);
1331
+ },
1332
+ } satisfies AdapterTestDebugLogs,
1333
+ }
1334
+ : {}),
1335
+ };
1336
+ return adapter;
1337
+ };
1338
+
1339
+ function formatTransactionId(transactionId: number) {
1340
+ if (getColorDepth() < 8) {
1341
+ return `#${transactionId}`;
1342
+ }
1343
+ return `${TTY_COLORS.fg.magenta}#${transactionId}${TTY_COLORS.reset}`;
1344
+ }
1345
+
1346
+ function formatStep(step: number, total: number) {
1347
+ return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`;
1348
+ }
1349
+
1350
+ function formatMethod(method: string) {
1351
+ return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`;
1352
+ }
1353
+
1354
+ function formatAction(action: string) {
1355
+ return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`;
1356
+ }
1357
+
1358
+ /**
1359
+ * @deprecated Use `createAdapterFactory` instead. This export will be removed in a future version.
1360
+ * @alias
1361
+ */
1362
+ export const createAdapter = createAdapterFactory;