@better-auth/core 1.4.6-beta.2 → 1.4.6-beta.3

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 (56) hide show
  1. package/.turbo/turbo-build.log +30 -29
  2. package/dist/api/index.d.mts +1 -2
  3. package/dist/api/index.mjs +3 -2
  4. package/dist/async_hooks/index.d.mts +1 -1
  5. package/dist/async_hooks/index.mjs +2 -1
  6. package/dist/async_hooks-CrTStdt6.mjs +45 -0
  7. package/dist/context/index.d.mts +2 -3
  8. package/dist/context/index.mjs +3 -2
  9. package/dist/{context-DgQ9XGBl.mjs → context-su4uu82y.mjs} +1 -1
  10. package/dist/db/adapter/index.d.mts +2 -3
  11. package/dist/db/adapter/index.mjs +951 -1
  12. package/dist/db/index.d.mts +2 -3
  13. package/dist/db/index.mjs +2 -1
  14. package/dist/env/index.d.mts +1 -1
  15. package/dist/env/index.mjs +1 -1
  16. package/dist/error/index.mjs +3 -2
  17. package/dist/{error-BhAKg8LX.mjs → error-CMXuwPsa.mjs} +1 -1
  18. package/dist/get-tables-BGfrxIVZ.mjs +252 -0
  19. package/dist/{index-D_XSRX55.d.mts → index-BfhTkcnW.d.mts} +273 -8
  20. package/dist/{index-DgwIISs7.d.mts → index-Da4Ujjef.d.mts} +0 -1
  21. package/dist/index.d.mts +2 -3
  22. package/dist/oauth2/index.d.mts +1 -2
  23. package/dist/oauth2/index.mjs +1 -1
  24. package/dist/social-providers/index.d.mts +1 -2
  25. package/dist/social-providers/index.mjs +4 -4
  26. package/dist/utils/index.d.mts +10 -1
  27. package/dist/utils/index.mjs +3 -2
  28. package/dist/utils-BqQC77zO.mjs +43 -0
  29. package/package.json +2 -2
  30. package/src/async_hooks/convex.spec.ts +12 -0
  31. package/src/async_hooks/index.ts +60 -25
  32. package/src/db/adapter/factory.ts +1362 -0
  33. package/src/db/adapter/get-default-field-name.ts +59 -0
  34. package/src/db/adapter/get-default-model-name.ts +51 -0
  35. package/src/db/adapter/get-field-attributes.ts +62 -0
  36. package/src/db/adapter/get-field-name.ts +43 -0
  37. package/src/db/adapter/get-id-field.ts +141 -0
  38. package/src/db/adapter/get-model-name.ts +36 -0
  39. package/src/db/adapter/index.ts +4 -0
  40. package/src/db/adapter/types.ts +161 -0
  41. package/src/db/adapter/utils.ts +61 -0
  42. package/src/db/get-tables.ts +276 -0
  43. package/src/db/index.ts +2 -0
  44. package/src/db/test/get-tables.test.ts +62 -0
  45. package/src/oauth2/oauth-provider.ts +1 -1
  46. package/src/types/context.ts +10 -0
  47. package/src/types/helper.ts +4 -0
  48. package/src/utils/id.ts +5 -0
  49. package/src/utils/index.ts +3 -0
  50. package/src/utils/json.ts +25 -0
  51. package/src/utils/string.ts +3 -0
  52. package/dist/async_hooks-BfRfbd1J.mjs +0 -18
  53. package/dist/utils-C5EN75oV.mjs +0 -7
  54. /package/dist/{env-8yWFh7b8.mjs → env-D6s-lvJz.mjs} +0 -0
  55. /package/dist/{index-X1Fs3IbM.d.mts → index-D4vfN5ui.d.mts} +0 -0
  56. /package/dist/{oauth2-B2XPHgx5.mjs → oauth2-7k48hhcV.mjs} +0 -0
@@ -1 +1,951 @@
1
- export { };
1
+ import { t as getAuthTables } from "../../get-tables-BGfrxIVZ.mjs";
2
+ import { i as logger, o as getColorDepth, t as TTY_COLORS } from "../../env-D6s-lvJz.mjs";
3
+ import { n as safeJSONParse, r as generateId } from "../../utils-BqQC77zO.mjs";
4
+ import { t as BetterAuthError } from "../../error-CMXuwPsa.mjs";
5
+
6
+ //#region src/db/adapter/get-default-model-name.ts
7
+ const initGetDefaultModelName = ({ usePlural, schema }) => {
8
+ /**
9
+ * This function helps us get the default model name from the schema defined by devs.
10
+ * Often times, the user will be using the `modelName` which could had been customized by the users.
11
+ * This function helps us get the actual model name useful to match against the schema. (eg: schema[model])
12
+ *
13
+ * If it's still unclear what this does:
14
+ *
15
+ * 1. User can define a custom modelName.
16
+ * 2. When using a custom modelName, doing something like `schema[model]` will not work.
17
+ * 3. Using this function helps us get the actual model name based on the user's defined custom modelName.
18
+ */
19
+ const getDefaultModelName = (model) => {
20
+ if (usePlural && model.charAt(model.length - 1) === "s") {
21
+ let pluralessModel = model.slice(0, -1);
22
+ let m$1 = schema[pluralessModel] ? pluralessModel : void 0;
23
+ if (!m$1) m$1 = Object.entries(schema).find(([_, f]) => f.modelName === pluralessModel)?.[0];
24
+ if (m$1) return m$1;
25
+ }
26
+ let m = schema[model] ? model : void 0;
27
+ if (!m) m = Object.entries(schema).find(([_, f]) => f.modelName === model)?.[0];
28
+ if (!m) throw new BetterAuthError(`Model "${model}" not found in schema`);
29
+ return m;
30
+ };
31
+ return getDefaultModelName;
32
+ };
33
+
34
+ //#endregion
35
+ //#region src/db/adapter/get-default-field-name.ts
36
+ const initGetDefaultFieldName = ({ schema, usePlural }) => {
37
+ const getDefaultModelName = initGetDefaultModelName({
38
+ schema,
39
+ usePlural
40
+ });
41
+ /**
42
+ * This function helps us get the default field name from the schema defined by devs.
43
+ * Often times, the user will be using the `fieldName` which could had been customized by the users.
44
+ * This function helps us get the actual field name useful to match against the schema. (eg: schema[model].fields[field])
45
+ *
46
+ * If it's still unclear what this does:
47
+ *
48
+ * 1. User can define a custom fieldName.
49
+ * 2. When using a custom fieldName, doing something like `schema[model].fields[field]` will not work.
50
+ */
51
+ const getDefaultFieldName = ({ field, model: unsafeModel }) => {
52
+ if (field === "id" || field === "_id") return "id";
53
+ const model = getDefaultModelName(unsafeModel);
54
+ let f = schema[model]?.fields[field];
55
+ if (!f) {
56
+ const result = Object.entries(schema[model].fields).find(([_, f$1]) => f$1.fieldName === field);
57
+ if (result) {
58
+ f = result[1];
59
+ field = result[0];
60
+ }
61
+ }
62
+ if (!f) throw new BetterAuthError(`Field ${field} not found in model ${model}`);
63
+ return field;
64
+ };
65
+ return getDefaultFieldName;
66
+ };
67
+
68
+ //#endregion
69
+ //#region src/db/adapter/get-id-field.ts
70
+ const initGetIdField = ({ usePlural, schema, disableIdGeneration, options, customIdGenerator, supportsUUIDs }) => {
71
+ const getDefaultModelName = initGetDefaultModelName({
72
+ usePlural,
73
+ schema
74
+ });
75
+ const idField = ({ customModelName, forceAllowId }) => {
76
+ const useNumberId = options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial";
77
+ const useUUIDs = options.advanced?.database?.generateId === "uuid";
78
+ let shouldGenerateId = (() => {
79
+ if (disableIdGeneration) return false;
80
+ else if (useNumberId && !forceAllowId) return false;
81
+ else if (useUUIDs) return !supportsUUIDs;
82
+ else return true;
83
+ })();
84
+ const model = getDefaultModelName(customModelName ?? "id");
85
+ return {
86
+ type: useNumberId ? "number" : "string",
87
+ required: shouldGenerateId ? true : false,
88
+ ...shouldGenerateId ? { defaultValue() {
89
+ if (disableIdGeneration) return void 0;
90
+ let generateId$1 = options.advanced?.database?.generateId;
91
+ if (generateId$1 === false || useNumberId) return void 0;
92
+ if (typeof generateId$1 === "function") return generateId$1({ model });
93
+ if (customIdGenerator) return customIdGenerator({ model });
94
+ if (generateId$1 === "uuid") return crypto.randomUUID();
95
+ return generateId();
96
+ } } : {},
97
+ transform: {
98
+ input: (value) => {
99
+ if (!value) return void 0;
100
+ if (useNumberId) {
101
+ const numberValue = Number(value);
102
+ if (isNaN(numberValue)) return;
103
+ return numberValue;
104
+ }
105
+ if (useUUIDs) {
106
+ if (shouldGenerateId && !forceAllowId) return value;
107
+ if (disableIdGeneration) return void 0;
108
+ if (supportsUUIDs) return void 0;
109
+ if (forceAllowId && typeof value === "string") if (/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) return value;
110
+ else {
111
+ const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", "");
112
+ logger.warn("[Adapter Factory] - Invalid UUID value for field `id` provided when `forceAllowId` is true. Generating a new UUID.", stack);
113
+ }
114
+ if (typeof value !== "string" && !supportsUUIDs) return crypto.randomUUID();
115
+ return;
116
+ }
117
+ return value;
118
+ },
119
+ output: (value) => {
120
+ if (!value) return void 0;
121
+ return String(value);
122
+ }
123
+ }
124
+ };
125
+ };
126
+ return idField;
127
+ };
128
+
129
+ //#endregion
130
+ //#region src/db/adapter/get-field-attributes.ts
131
+ const initGetFieldAttributes = ({ usePlural, schema, options, customIdGenerator, disableIdGeneration }) => {
132
+ const getDefaultModelName = initGetDefaultModelName({
133
+ usePlural,
134
+ schema
135
+ });
136
+ const getDefaultFieldName = initGetDefaultFieldName({
137
+ usePlural,
138
+ schema
139
+ });
140
+ const idField = initGetIdField({
141
+ usePlural,
142
+ schema,
143
+ options,
144
+ customIdGenerator,
145
+ disableIdGeneration
146
+ });
147
+ const getFieldAttributes = ({ model, field }) => {
148
+ const defaultModelName = getDefaultModelName(model);
149
+ const defaultFieldName = getDefaultFieldName({
150
+ field,
151
+ model: defaultModelName
152
+ });
153
+ const fields = schema[defaultModelName].fields;
154
+ fields.id = idField({ customModelName: defaultModelName });
155
+ const fieldAttributes = fields[defaultFieldName];
156
+ if (!fieldAttributes) throw new BetterAuthError(`Field ${field} not found in model ${model}`);
157
+ return fieldAttributes;
158
+ };
159
+ return getFieldAttributes;
160
+ };
161
+
162
+ //#endregion
163
+ //#region src/db/adapter/get-field-name.ts
164
+ const initGetFieldName = ({ schema, usePlural }) => {
165
+ const getDefaultModelName = initGetDefaultModelName({
166
+ schema,
167
+ usePlural
168
+ });
169
+ const getDefaultFieldName = initGetDefaultFieldName({
170
+ schema,
171
+ usePlural
172
+ });
173
+ /**
174
+ * Get the field name which is expected to be saved in the database based on the user's schema.
175
+ *
176
+ * This function is useful if you need to save the field name to the database.
177
+ *
178
+ * For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema.
179
+ */
180
+ function getFieldName({ model: modelName, field: fieldName }) {
181
+ const model = getDefaultModelName(modelName);
182
+ const field = getDefaultFieldName({
183
+ model,
184
+ field: fieldName
185
+ });
186
+ return schema[model]?.fields[field]?.fieldName || field;
187
+ }
188
+ return getFieldName;
189
+ };
190
+
191
+ //#endregion
192
+ //#region src/db/adapter/get-model-name.ts
193
+ const initGetModelName = ({ usePlural, schema }) => {
194
+ const getDefaultModelName = initGetDefaultModelName({
195
+ schema,
196
+ usePlural
197
+ });
198
+ /**
199
+ * Users can overwrite the default model of some tables. This function helps find the correct model name.
200
+ * Furthermore, if the user passes `usePlural` as true in their adapter config,
201
+ * then we should return the model name ending with an `s`.
202
+ */
203
+ const getModelName = (model) => {
204
+ const defaultModelKey = getDefaultModelName(model);
205
+ if (schema && schema[defaultModelKey] && schema[defaultModelKey].modelName !== model) return usePlural ? `${schema[defaultModelKey].modelName}s` : schema[defaultModelKey].modelName;
206
+ return usePlural ? `${model}s` : model;
207
+ };
208
+ return getModelName;
209
+ };
210
+
211
+ //#endregion
212
+ //#region src/db/adapter/utils.ts
213
+ function withApplyDefault(value, field, action) {
214
+ if (action === "update") {
215
+ if (value === void 0 && field.onUpdate !== void 0) {
216
+ if (typeof field.onUpdate === "function") return field.onUpdate();
217
+ return field.onUpdate;
218
+ }
219
+ return value;
220
+ }
221
+ if (action === "create") {
222
+ if (value === void 0 || field.required === true && value === null) {
223
+ if (field.defaultValue !== void 0) {
224
+ if (typeof field.defaultValue === "function") return field.defaultValue();
225
+ return field.defaultValue;
226
+ }
227
+ }
228
+ }
229
+ return value;
230
+ }
231
+ function isObject(item) {
232
+ return item !== null && typeof item === "object" && !Array.isArray(item);
233
+ }
234
+ function deepmerge(target, source) {
235
+ if (Array.isArray(target) && Array.isArray(source)) return [...target, ...source];
236
+ else if (isObject(target) && isObject(source)) {
237
+ const result = { ...target };
238
+ for (const [key, value] of Object.entries(source)) {
239
+ if (value === void 0) continue;
240
+ if (key in target) result[key] = deepmerge(target[key], value);
241
+ else result[key] = value;
242
+ }
243
+ return result;
244
+ }
245
+ return source;
246
+ }
247
+
248
+ //#endregion
249
+ //#region src/db/adapter/factory.ts
250
+ let debugLogs = [];
251
+ let transactionId = -1;
252
+ const createAsIsTransaction = (adapter) => (fn) => fn(adapter);
253
+ const createAdapterFactory = ({ adapter: customAdapter, config: cfg }) => (options) => {
254
+ const uniqueAdapterFactoryInstanceId = Math.random().toString(36).substring(2, 15);
255
+ const config = {
256
+ ...cfg,
257
+ supportsBooleans: cfg.supportsBooleans ?? true,
258
+ supportsDates: cfg.supportsDates ?? true,
259
+ supportsJSON: cfg.supportsJSON ?? false,
260
+ adapterName: cfg.adapterName ?? cfg.adapterId,
261
+ supportsNumericIds: cfg.supportsNumericIds ?? true,
262
+ supportsUUIDs: cfg.supportsUUIDs ?? false,
263
+ transaction: cfg.transaction ?? false,
264
+ disableTransformInput: cfg.disableTransformInput ?? false,
265
+ disableTransformOutput: cfg.disableTransformOutput ?? false,
266
+ disableTransformJoin: cfg.disableTransformJoin ?? false
267
+ };
268
+ if ((options.advanced?.database?.useNumberId === true || options.advanced?.database?.generateId === "serial") && config.supportsNumericIds === false) throw new BetterAuthError(`[${config.adapterName}] Your database or database adapter does not support numeric ids. Please disable "useNumberId" in your config.`);
269
+ const schema = getAuthTables(options);
270
+ const debugLog = (...args) => {
271
+ if (config.debugLogs === true || typeof config.debugLogs === "object") {
272
+ if (typeof config.debugLogs === "object" && "isRunningAdapterTests" in config.debugLogs) {
273
+ if (config.debugLogs.isRunningAdapterTests) {
274
+ args.shift();
275
+ debugLogs.push({
276
+ instance: uniqueAdapterFactoryInstanceId,
277
+ args
278
+ });
279
+ }
280
+ return;
281
+ }
282
+ if (typeof config.debugLogs === "object" && config.debugLogs.logCondition && !config.debugLogs.logCondition?.()) return;
283
+ if (typeof args[0] === "object" && "method" in args[0]) {
284
+ const method = args.shift().method;
285
+ if (typeof config.debugLogs === "object") {
286
+ if (method === "create" && !config.debugLogs.create) return;
287
+ else if (method === "update" && !config.debugLogs.update) return;
288
+ else if (method === "updateMany" && !config.debugLogs.updateMany) return;
289
+ else if (method === "findOne" && !config.debugLogs.findOne) return;
290
+ else if (method === "findMany" && !config.debugLogs.findMany) return;
291
+ else if (method === "delete" && !config.debugLogs.delete) return;
292
+ else if (method === "deleteMany" && !config.debugLogs.deleteMany) return;
293
+ else if (method === "count" && !config.debugLogs.count) return;
294
+ }
295
+ logger.info(`[${config.adapterName}]`, ...args);
296
+ } else logger.info(`[${config.adapterName}]`, ...args);
297
+ }
298
+ };
299
+ const getDefaultModelName = initGetDefaultModelName({
300
+ usePlural: config.usePlural,
301
+ schema
302
+ });
303
+ const getDefaultFieldName = initGetDefaultFieldName({
304
+ usePlural: config.usePlural,
305
+ schema
306
+ });
307
+ const getModelName = initGetModelName({
308
+ usePlural: config.usePlural,
309
+ schema
310
+ });
311
+ const getFieldName = initGetFieldName({
312
+ schema,
313
+ usePlural: config.usePlural
314
+ });
315
+ const idField = initGetIdField({
316
+ schema,
317
+ options,
318
+ usePlural: config.usePlural,
319
+ disableIdGeneration: config.disableIdGeneration,
320
+ customIdGenerator: config.customIdGenerator,
321
+ supportsUUIDs: config.supportsUUIDs
322
+ });
323
+ const getFieldAttributes = initGetFieldAttributes({
324
+ schema,
325
+ options,
326
+ usePlural: config.usePlural,
327
+ disableIdGeneration: config.disableIdGeneration,
328
+ customIdGenerator: config.customIdGenerator
329
+ });
330
+ const transformInput = async (data, defaultModelName, action, forceAllowId) => {
331
+ const transformedData = {};
332
+ const fields = schema[defaultModelName].fields;
333
+ const newMappedKeys = config.mapKeysTransformInput ?? {};
334
+ const useNumberId = options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial";
335
+ fields.id = idField({
336
+ customModelName: defaultModelName,
337
+ forceAllowId: forceAllowId && "id" in data
338
+ });
339
+ for (const field in fields) {
340
+ let value = data[field];
341
+ const fieldAttributes = fields[field];
342
+ let newFieldName = newMappedKeys[field] || fields[field].fieldName || field;
343
+ if (value === void 0 && (fieldAttributes.defaultValue === void 0 && !fieldAttributes.transform?.input && !(action === "update" && fieldAttributes.onUpdate) || action === "update" && !fieldAttributes.onUpdate)) continue;
344
+ if (fieldAttributes && fieldAttributes.type === "date" && !(value instanceof Date) && typeof value === "string") try {
345
+ value = new Date(value);
346
+ } catch {
347
+ logger.error("[Adapter Factory] Failed to convert string to date", {
348
+ value,
349
+ field
350
+ });
351
+ }
352
+ let newValue = withApplyDefault(value, fieldAttributes, action);
353
+ if (fieldAttributes.transform?.input) newValue = await fieldAttributes.transform.input(newValue);
354
+ if (fieldAttributes.references?.field === "id" && useNumberId) if (Array.isArray(newValue)) newValue = newValue.map((x) => x !== null ? Number(x) : null);
355
+ else newValue = newValue !== null ? Number(newValue) : null;
356
+ else if (config.supportsJSON === false && typeof newValue === "object" && fieldAttributes.type === "json") newValue = JSON.stringify(newValue);
357
+ else if (config.supportsJSON === false && Array.isArray(newValue) && (fieldAttributes.type === "string[]" || fieldAttributes.type === "number[]")) newValue = JSON.stringify(newValue);
358
+ else if (config.supportsDates === false && newValue instanceof Date && fieldAttributes.type === "date") newValue = newValue.toISOString();
359
+ else if (config.supportsBooleans === false && typeof newValue === "boolean") newValue = newValue ? 1 : 0;
360
+ if (config.customTransformInput) newValue = config.customTransformInput({
361
+ data: newValue,
362
+ action,
363
+ field: newFieldName,
364
+ fieldAttributes,
365
+ model: getModelName(defaultModelName),
366
+ schema,
367
+ options
368
+ });
369
+ if (newValue !== void 0) transformedData[newFieldName] = newValue;
370
+ }
371
+ return transformedData;
372
+ };
373
+ const transformOutput = async (data, unsafe_model, select = [], join) => {
374
+ const transformSingleOutput = async (data$1, unsafe_model$1, select$1 = []) => {
375
+ if (!data$1) return null;
376
+ const newMappedKeys = config.mapKeysTransformOutput ?? {};
377
+ const transformedData$1 = {};
378
+ const tableSchema = schema[getDefaultModelName(unsafe_model$1)].fields;
379
+ const idKey = Object.entries(newMappedKeys).find(([_, v]) => v === "id")?.[0];
380
+ tableSchema[idKey ?? "id"] = { type: options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial" ? "number" : "string" };
381
+ for (const key in tableSchema) {
382
+ if (select$1.length && !select$1.includes(key)) continue;
383
+ const field = tableSchema[key];
384
+ if (field) {
385
+ const originalKey = field.fieldName || key;
386
+ let newValue = data$1[Object.entries(newMappedKeys).find(([_, v]) => v === originalKey)?.[0] || originalKey];
387
+ if (field.transform?.output) newValue = await field.transform.output(newValue);
388
+ let newFieldName = newMappedKeys[key] || key;
389
+ if (originalKey === "id" || field.references?.field === "id") {
390
+ if (typeof newValue !== "undefined" && newValue !== null) newValue = String(newValue);
391
+ } else if (config.supportsJSON === false && typeof newValue === "string" && field.type === "json") newValue = safeJSONParse(newValue);
392
+ else if (config.supportsJSON === false && typeof newValue === "string" && (field.type === "string[]" || field.type === "number[]")) newValue = safeJSONParse(newValue);
393
+ else if (config.supportsDates === false && typeof newValue === "string" && field.type === "date") newValue = new Date(newValue);
394
+ else if (config.supportsBooleans === false && typeof newValue === "number" && field.type === "boolean") newValue = newValue === 1;
395
+ if (config.customTransformOutput) newValue = config.customTransformOutput({
396
+ data: newValue,
397
+ field: newFieldName,
398
+ fieldAttributes: field,
399
+ select: select$1,
400
+ model: getModelName(unsafe_model$1),
401
+ schema,
402
+ options
403
+ });
404
+ transformedData$1[newFieldName] = newValue;
405
+ }
406
+ }
407
+ return transformedData$1;
408
+ };
409
+ if (!join || Object.keys(join).length === 0) return await transformSingleOutput(data, unsafe_model, select);
410
+ unsafe_model = getDefaultModelName(unsafe_model);
411
+ let transformedData = await transformSingleOutput(data, unsafe_model, select);
412
+ const requiredModels = Object.entries(join).map(([model, joinConfig]) => ({
413
+ modelName: getModelName(model),
414
+ defaultModelName: getDefaultModelName(model),
415
+ joinConfig
416
+ }));
417
+ if (!data) return null;
418
+ for (const { modelName, defaultModelName, joinConfig } of requiredModels) {
419
+ let joinedData = await (async () => {
420
+ if (options.experimental?.joins) return data[modelName];
421
+ else return await handleFallbackJoin({
422
+ baseModel: unsafe_model,
423
+ baseData: transformedData,
424
+ joinModel: modelName,
425
+ specificJoinConfig: joinConfig
426
+ });
427
+ })();
428
+ if (joinedData === void 0 || joinedData === null) joinedData = joinConfig.relation === "one-to-one" ? null : [];
429
+ if (joinConfig.relation === "one-to-many" && !Array.isArray(joinedData)) joinedData = [joinedData];
430
+ let transformed = [];
431
+ if (Array.isArray(joinedData)) for (const item of joinedData) {
432
+ const transformedItem = await transformSingleOutput(item, modelName, []);
433
+ transformed.push(transformedItem);
434
+ }
435
+ else {
436
+ const transformedItem = await transformSingleOutput(joinedData, modelName, []);
437
+ transformed.push(transformedItem);
438
+ }
439
+ transformedData[defaultModelName] = (joinConfig.relation === "one-to-one" ? transformed[0] : transformed) ?? null;
440
+ }
441
+ return transformedData;
442
+ };
443
+ const transformWhereClause = ({ model, where }) => {
444
+ if (!where) return void 0;
445
+ const newMappedKeys = config.mapKeysTransformInput ?? {};
446
+ return where.map((w) => {
447
+ const { field: unsafe_field, value, operator = "eq", connector = "AND" } = w;
448
+ if (operator === "in") {
449
+ if (!Array.isArray(value)) throw new BetterAuthError("Value must be an array");
450
+ }
451
+ let newValue = value;
452
+ const defaultModelName = getDefaultModelName(model);
453
+ const defaultFieldName = getDefaultFieldName({
454
+ field: unsafe_field,
455
+ model
456
+ });
457
+ const fieldName = newMappedKeys[defaultFieldName] || getFieldName({
458
+ field: defaultFieldName,
459
+ model: defaultModelName
460
+ });
461
+ const fieldAttr = getFieldAttributes({
462
+ field: defaultFieldName,
463
+ model: defaultModelName
464
+ });
465
+ const useNumberId = options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial";
466
+ if (defaultFieldName === "id" || fieldAttr.references?.field === "id") {
467
+ if (useNumberId) if (Array.isArray(value)) newValue = value.map(Number);
468
+ else newValue = Number(value);
469
+ }
470
+ if (fieldAttr.type === "date" && value instanceof Date && !config.supportsDates) newValue = value.toISOString();
471
+ if (fieldAttr.type === "boolean" && typeof value === "boolean" && !config.supportsBooleans) newValue = value ? 1 : 0;
472
+ if (fieldAttr.type === "json" && typeof value === "object" && !config.supportsJSON) try {
473
+ newValue = JSON.stringify(value);
474
+ } catch (error) {
475
+ throw new Error(`Failed to stringify JSON value for field ${fieldName}`, { cause: error });
476
+ }
477
+ return {
478
+ operator,
479
+ connector,
480
+ field: fieldName,
481
+ value: newValue
482
+ };
483
+ });
484
+ };
485
+ const transformJoinClause = (baseModel, unsanitizedJoin, select) => {
486
+ if (!unsanitizedJoin) return void 0;
487
+ if (Object.keys(unsanitizedJoin).length === 0) return void 0;
488
+ const transformedJoin = {};
489
+ for (const [model, join] of Object.entries(unsanitizedJoin)) {
490
+ if (!join) continue;
491
+ const defaultModelName = getDefaultModelName(model);
492
+ const defaultBaseModelName = getDefaultModelName(baseModel);
493
+ let foreignKeys = Object.entries(schema[defaultModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultBaseModelName);
494
+ let isForwardJoin = true;
495
+ if (!foreignKeys.length) {
496
+ foreignKeys = Object.entries(schema[defaultBaseModelName].fields).filter(([field, fieldAttributes]) => fieldAttributes.references && getDefaultModelName(fieldAttributes.references.model) === defaultModelName);
497
+ isForwardJoin = false;
498
+ }
499
+ if (!foreignKeys.length) throw new BetterAuthError(`No foreign key found for model ${model} and base model ${baseModel} while performing join operation.`);
500
+ else if (foreignKeys.length > 1) throw new BetterAuthError(`Multiple foreign keys found for model ${model} and base model ${baseModel} while performing join operation. Only one foreign key is supported.`);
501
+ const [foreignKey, foreignKeyAttributes] = foreignKeys[0];
502
+ if (!foreignKeyAttributes.references) throw new BetterAuthError(`No references found for foreign key ${foreignKey} on model ${model} while performing join operation.`);
503
+ let from;
504
+ let to;
505
+ let requiredSelectField;
506
+ if (isForwardJoin) {
507
+ requiredSelectField = foreignKeyAttributes.references.field;
508
+ from = getFieldName({
509
+ model: baseModel,
510
+ field: requiredSelectField
511
+ });
512
+ to = getFieldName({
513
+ model,
514
+ field: foreignKey
515
+ });
516
+ } else {
517
+ requiredSelectField = foreignKey;
518
+ from = getFieldName({
519
+ model: baseModel,
520
+ field: requiredSelectField
521
+ });
522
+ to = getFieldName({
523
+ model,
524
+ field: foreignKeyAttributes.references.field
525
+ });
526
+ }
527
+ if (select && !select.includes(requiredSelectField)) select.push(requiredSelectField);
528
+ const isUnique = to === "id" ? true : foreignKeyAttributes.unique ?? false;
529
+ let limit = options.advanced?.database?.defaultFindManyLimit ?? 100;
530
+ if (isUnique) limit = 1;
531
+ else if (typeof join === "object" && typeof join.limit === "number") limit = join.limit;
532
+ transformedJoin[getModelName(model)] = {
533
+ on: {
534
+ from,
535
+ to
536
+ },
537
+ limit,
538
+ relation: isUnique ? "one-to-one" : "one-to-many"
539
+ };
540
+ }
541
+ return {
542
+ join: transformedJoin,
543
+ select
544
+ };
545
+ };
546
+ /**
547
+ * Handle joins by making separate queries and combining results (fallback for adapters that don't support native joins).
548
+ */
549
+ const handleFallbackJoin = async ({ baseModel, baseData, joinModel, specificJoinConfig: joinConfig }) => {
550
+ if (!baseData) return baseData;
551
+ const modelName = getModelName(joinModel);
552
+ const field = joinConfig.on.to;
553
+ const value = baseData[getDefaultFieldName({
554
+ field: joinConfig.on.from,
555
+ model: baseModel
556
+ })];
557
+ if (value === null || value === void 0) return joinConfig.relation === "one-to-one" ? null : [];
558
+ let result;
559
+ const where = transformWhereClause({
560
+ model: modelName,
561
+ where: [{
562
+ field,
563
+ value,
564
+ operator: "eq",
565
+ connector: "AND"
566
+ }]
567
+ });
568
+ try {
569
+ if (joinConfig.relation === "one-to-one") result = await adapterInstance.findOne({
570
+ model: modelName,
571
+ where
572
+ });
573
+ else {
574
+ const limit = joinConfig.limit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;
575
+ result = await adapterInstance.findMany({
576
+ model: modelName,
577
+ where,
578
+ limit
579
+ });
580
+ }
581
+ } catch (error) {
582
+ logger.error(`Failed to query fallback join for model ${modelName}:`, {
583
+ where,
584
+ limit: joinConfig.limit
585
+ });
586
+ console.error(error);
587
+ throw error;
588
+ }
589
+ return result;
590
+ };
591
+ const adapterInstance = customAdapter({
592
+ options,
593
+ schema,
594
+ debugLog,
595
+ getFieldName,
596
+ getModelName,
597
+ getDefaultModelName,
598
+ getDefaultFieldName,
599
+ getFieldAttributes,
600
+ transformInput,
601
+ transformOutput,
602
+ transformWhereClause
603
+ });
604
+ let lazyLoadTransaction = null;
605
+ const adapter = {
606
+ transaction: async (cb) => {
607
+ if (!lazyLoadTransaction) if (!config.transaction) lazyLoadTransaction = createAsIsTransaction(adapter);
608
+ else {
609
+ logger.debug(`[${config.adapterName}] - Using provided transaction implementation.`);
610
+ lazyLoadTransaction = config.transaction;
611
+ }
612
+ return lazyLoadTransaction(cb);
613
+ },
614
+ create: async ({ data: unsafeData, model: unsafeModel, select, forceAllowId = false }) => {
615
+ transactionId++;
616
+ let thisTransactionId = transactionId;
617
+ const model = getModelName(unsafeModel);
618
+ unsafeModel = getDefaultModelName(unsafeModel);
619
+ if ("id" in unsafeData && typeof unsafeData.id !== "undefined" && !forceAllowId) {
620
+ logger.warn(`[${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.`);
621
+ const stack = (/* @__PURE__ */ new Error()).stack?.split("\n").filter((_, i) => i !== 1).join("\n").replace("Error:", "Create method with `id` being called at:");
622
+ console.log(stack);
623
+ unsafeData.id = void 0;
624
+ }
625
+ debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("create")} ${formatAction("Unsafe Input")}:`, {
626
+ model,
627
+ data: unsafeData
628
+ });
629
+ let data = unsafeData;
630
+ if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "create", forceAllowId);
631
+ debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Input")}:`, {
632
+ model,
633
+ data
634
+ });
635
+ const res = await adapterInstance.create({
636
+ data,
637
+ model
638
+ });
639
+ debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("create")} ${formatAction("DB Result")}:`, {
640
+ model,
641
+ res
642
+ });
643
+ let transformed = res;
644
+ if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, void 0);
645
+ debugLog({ method: "create" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("create")} ${formatAction("Parsed Result")}:`, {
646
+ model,
647
+ data: transformed
648
+ });
649
+ return transformed;
650
+ },
651
+ update: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {
652
+ transactionId++;
653
+ let thisTransactionId = transactionId;
654
+ unsafeModel = getDefaultModelName(unsafeModel);
655
+ const model = getModelName(unsafeModel);
656
+ const where = transformWhereClause({
657
+ model: unsafeModel,
658
+ where: unsafeWhere
659
+ });
660
+ debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("update")} ${formatAction("Unsafe Input")}:`, {
661
+ model,
662
+ data: unsafeData
663
+ });
664
+ let data = unsafeData;
665
+ if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update");
666
+ debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Input")}:`, {
667
+ model,
668
+ data
669
+ });
670
+ const res = await adapterInstance.update({
671
+ model,
672
+ where,
673
+ update: data
674
+ });
675
+ debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("update")} ${formatAction("DB Result")}:`, {
676
+ model,
677
+ data: res
678
+ });
679
+ let transformed = res;
680
+ if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, void 0, void 0);
681
+ debugLog({ method: "update" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("update")} ${formatAction("Parsed Result")}:`, {
682
+ model,
683
+ data: transformed
684
+ });
685
+ return transformed;
686
+ },
687
+ updateMany: async ({ model: unsafeModel, where: unsafeWhere, update: unsafeData }) => {
688
+ transactionId++;
689
+ let thisTransactionId = transactionId;
690
+ const model = getModelName(unsafeModel);
691
+ const where = transformWhereClause({
692
+ model: unsafeModel,
693
+ where: unsafeWhere
694
+ });
695
+ unsafeModel = getDefaultModelName(unsafeModel);
696
+ debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 4)}`, `${formatMethod("updateMany")} ${formatAction("Unsafe Input")}:`, {
697
+ model,
698
+ data: unsafeData
699
+ });
700
+ let data = unsafeData;
701
+ if (!config.disableTransformInput) data = await transformInput(unsafeData, unsafeModel, "update");
702
+ debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Input")}:`, {
703
+ model,
704
+ data
705
+ });
706
+ const updatedCount = await adapterInstance.updateMany({
707
+ model,
708
+ where,
709
+ update: data
710
+ });
711
+ debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 4)}`, `${formatMethod("updateMany")} ${formatAction("DB Result")}:`, {
712
+ model,
713
+ data: updatedCount
714
+ });
715
+ debugLog({ method: "updateMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(4, 4)}`, `${formatMethod("updateMany")} ${formatAction("Parsed Result")}:`, {
716
+ model,
717
+ data: updatedCount
718
+ });
719
+ return updatedCount;
720
+ },
721
+ findOne: async ({ model: unsafeModel, where: unsafeWhere, select, join: unsafeJoin }) => {
722
+ transactionId++;
723
+ let thisTransactionId = transactionId;
724
+ const model = getModelName(unsafeModel);
725
+ const where = transformWhereClause({
726
+ model: unsafeModel,
727
+ where: unsafeWhere
728
+ });
729
+ unsafeModel = getDefaultModelName(unsafeModel);
730
+ let join;
731
+ let passJoinToAdapter = true;
732
+ if (!config.disableTransformJoin) {
733
+ const result = transformJoinClause(unsafeModel, unsafeJoin, select);
734
+ if (result) {
735
+ join = result.join;
736
+ select = result.select;
737
+ }
738
+ if (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false;
739
+ } else join = unsafeJoin;
740
+ debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findOne")}:`, {
741
+ model,
742
+ where,
743
+ select,
744
+ join
745
+ });
746
+ const res = await adapterInstance.findOne({
747
+ model,
748
+ where,
749
+ select,
750
+ join: passJoinToAdapter ? join : void 0
751
+ });
752
+ debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findOne")} ${formatAction("DB Result")}:`, {
753
+ model,
754
+ data: res
755
+ });
756
+ let transformed = res;
757
+ if (!config.disableTransformOutput) transformed = await transformOutput(res, unsafeModel, select, join);
758
+ debugLog({ method: "findOne" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findOne")} ${formatAction("Parsed Result")}:`, {
759
+ model,
760
+ data: transformed
761
+ });
762
+ return transformed;
763
+ },
764
+ findMany: async ({ model: unsafeModel, where: unsafeWhere, limit: unsafeLimit, sortBy, offset, join: unsafeJoin }) => {
765
+ transactionId++;
766
+ let thisTransactionId = transactionId;
767
+ const limit = unsafeLimit ?? options.advanced?.database?.defaultFindManyLimit ?? 100;
768
+ const model = getModelName(unsafeModel);
769
+ const where = transformWhereClause({
770
+ model: unsafeModel,
771
+ where: unsafeWhere
772
+ });
773
+ unsafeModel = getDefaultModelName(unsafeModel);
774
+ let join;
775
+ let passJoinToAdapter = true;
776
+ if (!config.disableTransformJoin) {
777
+ const result = transformJoinClause(unsafeModel, unsafeJoin, void 0);
778
+ if (result) join = result.join;
779
+ if (!options.experimental?.joins && join && Object.keys(join).length > 0) passJoinToAdapter = false;
780
+ } else join = unsafeJoin;
781
+ debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 3)}`, `${formatMethod("findMany")}:`, {
782
+ model,
783
+ where,
784
+ limit,
785
+ sortBy,
786
+ offset,
787
+ join
788
+ });
789
+ const res = await adapterInstance.findMany({
790
+ model,
791
+ where,
792
+ limit,
793
+ sortBy,
794
+ offset,
795
+ join: passJoinToAdapter ? join : void 0
796
+ });
797
+ debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 3)}`, `${formatMethod("findMany")} ${formatAction("DB Result")}:`, {
798
+ model,
799
+ data: res
800
+ });
801
+ let transformed = res;
802
+ if (!config.disableTransformOutput) transformed = await Promise.all(res.map(async (r) => {
803
+ return await transformOutput(r, unsafeModel, void 0, join);
804
+ }));
805
+ debugLog({ method: "findMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(3, 3)}`, `${formatMethod("findMany")} ${formatAction("Parsed Result")}:`, {
806
+ model,
807
+ data: transformed
808
+ });
809
+ return transformed;
810
+ },
811
+ delete: async ({ model: unsafeModel, where: unsafeWhere }) => {
812
+ transactionId++;
813
+ let thisTransactionId = transactionId;
814
+ const model = getModelName(unsafeModel);
815
+ const where = transformWhereClause({
816
+ model: unsafeModel,
817
+ where: unsafeWhere
818
+ });
819
+ unsafeModel = getDefaultModelName(unsafeModel);
820
+ debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("delete")}:`, {
821
+ model,
822
+ where
823
+ });
824
+ await adapterInstance.delete({
825
+ model,
826
+ where
827
+ });
828
+ debugLog({ method: "delete" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("delete")} ${formatAction("DB Result")}:`, { model });
829
+ },
830
+ deleteMany: async ({ model: unsafeModel, where: unsafeWhere }) => {
831
+ transactionId++;
832
+ let thisTransactionId = transactionId;
833
+ const model = getModelName(unsafeModel);
834
+ const where = transformWhereClause({
835
+ model: unsafeModel,
836
+ where: unsafeWhere
837
+ });
838
+ unsafeModel = getDefaultModelName(unsafeModel);
839
+ debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DeleteMany")}:`, {
840
+ model,
841
+ where
842
+ });
843
+ const res = await adapterInstance.deleteMany({
844
+ model,
845
+ where
846
+ });
847
+ debugLog({ method: "deleteMany" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("deleteMany")} ${formatAction("DB Result")}:`, {
848
+ model,
849
+ data: res
850
+ });
851
+ return res;
852
+ },
853
+ count: async ({ model: unsafeModel, where: unsafeWhere }) => {
854
+ transactionId++;
855
+ let thisTransactionId = transactionId;
856
+ const model = getModelName(unsafeModel);
857
+ const where = transformWhereClause({
858
+ model: unsafeModel,
859
+ where: unsafeWhere
860
+ });
861
+ unsafeModel = getDefaultModelName(unsafeModel);
862
+ debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(1, 2)}`, `${formatMethod("count")}:`, {
863
+ model,
864
+ where
865
+ });
866
+ const res = await adapterInstance.count({
867
+ model,
868
+ where
869
+ });
870
+ debugLog({ method: "count" }, `${formatTransactionId(thisTransactionId)} ${formatStep(2, 2)}`, `${formatMethod("count")}:`, {
871
+ model,
872
+ data: res
873
+ });
874
+ return res;
875
+ },
876
+ createSchema: adapterInstance.createSchema ? async (_, file) => {
877
+ const tables = getAuthTables(options);
878
+ if (options.secondaryStorage && !options.session?.storeSessionInDatabase) delete tables.session;
879
+ if (options.rateLimit && options.rateLimit.storage === "database" && (typeof options.rateLimit.enabled === "undefined" || options.rateLimit.enabled === true)) tables.ratelimit = {
880
+ modelName: options.rateLimit.modelName ?? "ratelimit",
881
+ fields: {
882
+ key: {
883
+ type: "string",
884
+ unique: true,
885
+ required: true,
886
+ fieldName: options.rateLimit.fields?.key ?? "key"
887
+ },
888
+ count: {
889
+ type: "number",
890
+ required: true,
891
+ fieldName: options.rateLimit.fields?.count ?? "count"
892
+ },
893
+ lastRequest: {
894
+ type: "number",
895
+ required: true,
896
+ bigint: true,
897
+ defaultValue: () => Date.now(),
898
+ fieldName: options.rateLimit.fields?.lastRequest ?? "lastRequest"
899
+ }
900
+ }
901
+ };
902
+ return adapterInstance.createSchema({
903
+ file,
904
+ tables
905
+ });
906
+ } : void 0,
907
+ options: {
908
+ adapterConfig: config,
909
+ ...adapterInstance.options ?? {}
910
+ },
911
+ id: config.adapterId,
912
+ ...config.debugLogs?.isRunningAdapterTests ? { adapterTestDebugLogs: {
913
+ resetDebugLogs() {
914
+ debugLogs = debugLogs.filter((log) => log.instance !== uniqueAdapterFactoryInstanceId);
915
+ },
916
+ printDebugLogs() {
917
+ const separator = `─`.repeat(80);
918
+ const logs = debugLogs.filter((log$1) => log$1.instance === uniqueAdapterFactoryInstanceId);
919
+ if (logs.length === 0) return;
920
+ let log = logs.reverse().map((log$1) => {
921
+ log$1.args[0] = `\n${log$1.args[0]}`;
922
+ return [...log$1.args, "\n"];
923
+ }).reduce((prev, curr) => {
924
+ return [...curr, ...prev];
925
+ }, [`\n${separator}`]);
926
+ console.log(...log);
927
+ }
928
+ } } : {}
929
+ };
930
+ return adapter;
931
+ };
932
+ function formatTransactionId(transactionId$1) {
933
+ if (getColorDepth() < 8) return `#${transactionId$1}`;
934
+ return `${TTY_COLORS.fg.magenta}#${transactionId$1}${TTY_COLORS.reset}`;
935
+ }
936
+ function formatStep(step, total) {
937
+ return `${TTY_COLORS.bg.black}${TTY_COLORS.fg.yellow}[${step}/${total}]${TTY_COLORS.reset}`;
938
+ }
939
+ function formatMethod(method) {
940
+ return `${TTY_COLORS.bright}${method}${TTY_COLORS.reset}`;
941
+ }
942
+ function formatAction(action) {
943
+ return `${TTY_COLORS.dim}(${action})${TTY_COLORS.reset}`;
944
+ }
945
+ /**
946
+ * @deprecated Use `createAdapterFactory` instead. This export will be removed in a future version.
947
+ */
948
+ const createAdapter = createAdapterFactory;
949
+
950
+ //#endregion
951
+ export { createAdapter, createAdapterFactory, deepmerge, initGetDefaultFieldName, initGetDefaultModelName, initGetFieldAttributes, initGetFieldName, initGetIdField, initGetModelName, withApplyDefault };