@hammadj/better-auth-memory-adapter 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.
@@ -0,0 +1,33 @@
1
+
2
+ > @hammadj/better-auth-memory-adapter@1.5.0-beta.9 build /Users/hammadjutt/Dev/better-auth-fork/packages/memory-adapter
3
+ > tsdown
4
+
5
+ β„Ή tsdown v0.20.1 powered by rolldown v1.0.0-rc.1
6
+ β„Ή config file: /Users/hammadjutt/Dev/better-auth-fork/packages/memory-adapter/tsdown.config.ts
7
+ β„Ή entry: src/index.ts
8
+ β„Ή tsconfig: tsconfig.json
9
+ β„Ή Build start
10
+ β„Ή Cleaning 2 files
11
+ β„Ή dist/index.mjs  8.17 kB β”‚ gzip: 2.23 kB
12
+ β„Ή dist/index.mjs.map 17.75 kB β”‚ gzip: 4.64 kB
13
+ β„Ή dist/index.d.mts  0.54 kB β”‚ gzip: 0.29 kB
14
+ β„Ή 3 files, total: 26.46 kB
15
+ src/memory-adapter.ts (7:37) [UNRESOLVED_IMPORT] Warning: Could not resolve '@better-auth/core/db/adapter' in src/memory-adapter.ts
16
+ β•­─[ src/memory-adapter.ts:7:38 ]
17
+ β”‚
18
+ 7 β”‚ import { createAdapterFactory } from "@better-auth/core/db/adapter";
19
+  β”‚ ───────────────┬──────────────
20
+  β”‚ ╰──────────────── Module not found, treating it as an external dependency
21
+ ───╯
22
+
23
+ src/memory-adapter.ts (8:23) [UNRESOLVED_IMPORT] Warning: Could not resolve '@better-auth/core/env' in src/memory-adapter.ts
24
+ β•­─[ src/memory-adapter.ts:8:24 ]
25
+ β”‚
26
+ 8 β”‚ import { logger } from "@better-auth/core/env";
27
+  β”‚ ───────────┬───────────
28
+  β”‚ ╰───────────── Module not found, treating it as an external dependency
29
+ ───╯
30
+
31
+ [PLUGIN_TIMINGS] Warning: Your build spent significant time in plugin `rolldown-plugin-dts:generate`. See https://rolldown.rs/options/checks#plugintimings for more details.
32
+
33
+ βœ” Build complete in 5153ms
package/LICENSE.md ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+ Copyright (c) 2024 - present, Bereket Engida
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
5
+ this software and associated documentation files (the β€œSoftware”), to deal in
6
+ the Software without restriction, including without limitation the rights to
7
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8
+ the Software, and to permit persons to whom the Software is furnished to do so,
9
+ subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in all
12
+ copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED β€œAS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20
+ DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,14 @@
1
+ import { DBAdapterDebugLogOption } from "@better-auth/core/db/adapter";
2
+ import { BetterAuthOptions } from "@better-auth/core";
3
+
4
+ //#region src/memory-adapter.d.ts
5
+ interface MemoryDB {
6
+ [key: string]: any[];
7
+ }
8
+ interface MemoryAdapterConfig {
9
+ debugLogs?: DBAdapterDebugLogOption | undefined;
10
+ }
11
+ declare const memoryAdapter: (db: MemoryDB, config?: MemoryAdapterConfig | undefined) => (options: BetterAuthOptions) => any;
12
+ //#endregion
13
+ export { type MemoryAdapterConfig, type MemoryDB, memoryAdapter };
14
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1,214 @@
1
+ import { createAdapterFactory } from "@better-auth/core/db/adapter";
2
+ import { logger } from "@better-auth/core/env";
3
+
4
+ //#region src/memory-adapter.ts
5
+ const memoryAdapter = (db, config) => {
6
+ let lazyOptions = null;
7
+ const adapterCreator = createAdapterFactory({
8
+ config: {
9
+ adapterId: "memory",
10
+ adapterName: "Memory Adapter",
11
+ usePlural: false,
12
+ debugLogs: config?.debugLogs || false,
13
+ supportsArrays: true,
14
+ customTransformInput(props) {
15
+ if ((props.options.advanced?.database?.useNumberId || props.options.advanced?.database?.generateId === "serial") && props.field === "id" && props.action === "create") return db[props.model].length + 1;
16
+ return props.data;
17
+ },
18
+ transaction: async (cb) => {
19
+ const clone = structuredClone(db);
20
+ try {
21
+ return await cb(adapterCreator(lazyOptions));
22
+ } catch (error) {
23
+ Object.keys(db).forEach((key) => {
24
+ db[key] = clone[key];
25
+ });
26
+ throw error;
27
+ }
28
+ }
29
+ },
30
+ adapter: ({ getFieldName, options, getModelName }) => {
31
+ const applySortToRecords = (records, sortBy, model) => {
32
+ if (!sortBy) return records;
33
+ return records.sort((a, b) => {
34
+ const field = getFieldName({
35
+ model,
36
+ field: sortBy.field
37
+ });
38
+ const aValue = a[field];
39
+ const bValue = b[field];
40
+ let comparison = 0;
41
+ if (aValue == null && bValue == null) comparison = 0;
42
+ else if (aValue == null) comparison = -1;
43
+ else if (bValue == null) comparison = 1;
44
+ else if (typeof aValue === "string" && typeof bValue === "string") comparison = aValue.localeCompare(bValue);
45
+ else if (aValue instanceof Date && bValue instanceof Date) comparison = aValue.getTime() - bValue.getTime();
46
+ else if (typeof aValue === "number" && typeof bValue === "number") comparison = aValue - bValue;
47
+ else if (typeof aValue === "boolean" && typeof bValue === "boolean") comparison = aValue === bValue ? 0 : aValue ? 1 : -1;
48
+ else comparison = String(aValue).localeCompare(String(bValue));
49
+ return sortBy.direction === "asc" ? comparison : -comparison;
50
+ });
51
+ };
52
+ function convertWhereClause(where, model, join) {
53
+ const execute = (where, model) => {
54
+ const table = db[model];
55
+ if (!table) {
56
+ logger.error(`[MemoryAdapter] Model ${model} not found in the DB`, Object.keys(db));
57
+ throw new Error(`Model ${model} not found`);
58
+ }
59
+ const evalClause = (record, clause) => {
60
+ const { field, value, operator } = clause;
61
+ switch (operator) {
62
+ case "in":
63
+ if (!Array.isArray(value)) throw new Error("Value must be an array");
64
+ return value.includes(record[field]);
65
+ case "not_in":
66
+ if (!Array.isArray(value)) throw new Error("Value must be an array");
67
+ return !value.includes(record[field]);
68
+ case "contains": return record[field].includes(value);
69
+ case "starts_with": return record[field].startsWith(value);
70
+ case "ends_with": return record[field].endsWith(value);
71
+ case "ne": return record[field] !== value;
72
+ case "gt": return value != null && Boolean(record[field] > value);
73
+ case "gte": return value != null && Boolean(record[field] >= value);
74
+ case "lt": return value != null && Boolean(record[field] < value);
75
+ case "lte": return value != null && Boolean(record[field] <= value);
76
+ default: return record[field] === value;
77
+ }
78
+ };
79
+ return table.filter((record) => {
80
+ if (!where.length || where.length === 0) return true;
81
+ let result = evalClause(record, where[0]);
82
+ for (const clause of where) {
83
+ const clauseResult = evalClause(record, clause);
84
+ if (clause.connector === "OR") result = result || clauseResult;
85
+ else result = result && clauseResult;
86
+ }
87
+ return result;
88
+ });
89
+ };
90
+ if (!join) return execute(where, model);
91
+ const baseRecords = execute(where, model);
92
+ const grouped = /* @__PURE__ */ new Map();
93
+ const seenIds = /* @__PURE__ */ new Map();
94
+ for (const baseRecord of baseRecords) {
95
+ const baseId = String(baseRecord.id);
96
+ if (!grouped.has(baseId)) {
97
+ const nested = { ...baseRecord };
98
+ for (const [joinModel, joinAttr] of Object.entries(join)) {
99
+ const joinModelName = getModelName(joinModel);
100
+ if (joinAttr.relation === "one-to-one") nested[joinModelName] = null;
101
+ else {
102
+ nested[joinModelName] = [];
103
+ seenIds.set(`${baseId}-${joinModel}`, /* @__PURE__ */ new Set());
104
+ }
105
+ }
106
+ grouped.set(baseId, nested);
107
+ }
108
+ const nestedEntry = grouped.get(baseId);
109
+ for (const [joinModel, joinAttr] of Object.entries(join)) {
110
+ const joinModelName = getModelName(joinModel);
111
+ const joinTable = db[joinModelName];
112
+ if (!joinTable) {
113
+ logger.error(`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`, Object.keys(db));
114
+ throw new Error(`JoinOption model ${joinModelName} not found`);
115
+ }
116
+ const matchingRecords = joinTable.filter((joinRecord) => joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from]);
117
+ if (joinAttr.relation === "one-to-one") nestedEntry[joinModelName] = matchingRecords[0] || null;
118
+ else {
119
+ const seenSet = seenIds.get(`${baseId}-${joinModel}`);
120
+ const limit = joinAttr.limit ?? 100;
121
+ let count = 0;
122
+ for (const matchingRecord of matchingRecords) {
123
+ if (count >= limit) break;
124
+ if (!seenSet.has(matchingRecord.id)) {
125
+ nestedEntry[joinModelName].push(matchingRecord);
126
+ seenSet.add(matchingRecord.id);
127
+ count++;
128
+ }
129
+ }
130
+ }
131
+ }
132
+ }
133
+ return Array.from(grouped.values());
134
+ }
135
+ return {
136
+ create: async ({ model, data }) => {
137
+ if (options.advanced?.database?.useNumberId || options.advanced?.database?.generateId === "serial") data.id = db[getModelName(model)].length + 1;
138
+ if (!db[model]) db[model] = [];
139
+ db[model].push(data);
140
+ return data;
141
+ },
142
+ findOne: async ({ model, where, join }) => {
143
+ const res = convertWhereClause(where, model, join);
144
+ if (join) {
145
+ const resArray = res;
146
+ if (!resArray.length) return null;
147
+ return resArray[0];
148
+ }
149
+ return res[0] || null;
150
+ },
151
+ findMany: async ({ model, where, sortBy, limit, offset, join }) => {
152
+ const res = convertWhereClause(where || [], model, join);
153
+ if (join) {
154
+ const resArray = res;
155
+ if (!resArray.length) return [];
156
+ applySortToRecords(resArray, sortBy, model);
157
+ let paginatedRecords = resArray;
158
+ if (offset !== void 0) paginatedRecords = paginatedRecords.slice(offset);
159
+ if (limit !== void 0) paginatedRecords = paginatedRecords.slice(0, limit);
160
+ return paginatedRecords;
161
+ }
162
+ let table = applySortToRecords(res, sortBy, model);
163
+ if (offset !== void 0) table = table.slice(offset);
164
+ if (limit !== void 0) table = table.slice(0, limit);
165
+ return table || [];
166
+ },
167
+ count: async ({ model, where }) => {
168
+ if (where) return convertWhereClause(where, model).length;
169
+ return db[model].length;
170
+ },
171
+ update: async ({ model, where, update }) => {
172
+ const res = convertWhereClause(where, model);
173
+ res.forEach((record) => {
174
+ Object.assign(record, update);
175
+ });
176
+ return res[0] || null;
177
+ },
178
+ delete: async ({ model, where }) => {
179
+ const table = db[model];
180
+ const res = convertWhereClause(where, model);
181
+ db[model] = table.filter((record) => !res.includes(record));
182
+ },
183
+ deleteMany: async ({ model, where }) => {
184
+ const table = db[model];
185
+ const res = convertWhereClause(where, model);
186
+ let count = 0;
187
+ db[model] = table.filter((record) => {
188
+ if (res.includes(record)) {
189
+ count++;
190
+ return false;
191
+ }
192
+ return !res.includes(record);
193
+ });
194
+ return count;
195
+ },
196
+ updateMany({ model, where, update }) {
197
+ const res = convertWhereClause(where, model);
198
+ res.forEach((record) => {
199
+ Object.assign(record, update);
200
+ });
201
+ return res[0] || null;
202
+ }
203
+ };
204
+ }
205
+ });
206
+ return (options) => {
207
+ lazyOptions = options;
208
+ return adapterCreator(options);
209
+ };
210
+ };
211
+
212
+ //#endregion
213
+ export { memoryAdapter };
214
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/memory-adapter.ts"],"sourcesContent":["import type { BetterAuthOptions } from \"@better-auth/core\";\nimport type {\n\tCleanedWhere,\n\tDBAdapterDebugLogOption,\n\tJoinConfig,\n} from \"@better-auth/core/db/adapter\";\nimport { createAdapterFactory } from \"@better-auth/core/db/adapter\";\nimport { logger } from \"@better-auth/core/env\";\n\nexport interface MemoryDB {\n\t[key: string]: any[];\n}\n\nexport interface MemoryAdapterConfig {\n\tdebugLogs?: DBAdapterDebugLogOption | undefined;\n}\n\nexport const memoryAdapter = (\n\tdb: MemoryDB,\n\tconfig?: MemoryAdapterConfig | undefined,\n) => {\n\tlet lazyOptions: BetterAuthOptions | null = null;\n\tconst adapterCreator = createAdapterFactory({\n\t\tconfig: {\n\t\t\tadapterId: \"memory\",\n\t\t\tadapterName: \"Memory Adapter\",\n\t\t\tusePlural: false,\n\t\t\tdebugLogs: config?.debugLogs || false,\n\t\t\tsupportsArrays: true,\n\t\t\tcustomTransformInput(props) {\n\t\t\t\tconst useNumberId =\n\t\t\t\t\tprops.options.advanced?.database?.useNumberId ||\n\t\t\t\t\tprops.options.advanced?.database?.generateId === \"serial\";\n\t\t\t\tif (useNumberId && props.field === \"id\" && props.action === \"create\") {\n\t\t\t\t\treturn db[props.model]!.length + 1;\n\t\t\t\t}\n\t\t\t\treturn props.data;\n\t\t\t},\n\t\t\ttransaction: async (cb) => {\n\t\t\t\tconst clone = structuredClone(db);\n\t\t\t\ttry {\n\t\t\t\t\tconst r = await cb(adapterCreator(lazyOptions!));\n\t\t\t\t\treturn r;\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Rollback changes\n\t\t\t\t\tObject.keys(db).forEach((key) => {\n\t\t\t\t\t\tdb[key] = clone[key]!;\n\t\t\t\t\t});\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\tadapter: ({ getFieldName, options, getModelName }) => {\n\t\t\tconst applySortToRecords = (\n\t\t\t\trecords: any[],\n\t\t\t\tsortBy: { field: string; direction: \"asc\" | \"desc\" } | undefined,\n\t\t\t\tmodel: string,\n\t\t\t) => {\n\t\t\t\tif (!sortBy) return records;\n\t\t\t\treturn records.sort((a: any, b: any) => {\n\t\t\t\t\tconst field = getFieldName({ model, field: sortBy.field });\n\t\t\t\t\tconst aValue = a[field];\n\t\t\t\t\tconst bValue = b[field];\n\n\t\t\t\t\tlet comparison = 0;\n\n\t\t\t\t\t// Handle null/undefined values\n\t\t\t\t\tif (aValue == null && bValue == null) {\n\t\t\t\t\t\tcomparison = 0;\n\t\t\t\t\t} else if (aValue == null) {\n\t\t\t\t\t\tcomparison = -1;\n\t\t\t\t\t} else if (bValue == null) {\n\t\t\t\t\t\tcomparison = 1;\n\t\t\t\t\t}\n\t\t\t\t\t// Handle string comparison\n\t\t\t\t\telse if (typeof aValue === \"string\" && typeof bValue === \"string\") {\n\t\t\t\t\t\tcomparison = aValue.localeCompare(bValue);\n\t\t\t\t\t}\n\t\t\t\t\t// Handle date comparison\n\t\t\t\t\telse if (aValue instanceof Date && bValue instanceof Date) {\n\t\t\t\t\t\tcomparison = aValue.getTime() - bValue.getTime();\n\t\t\t\t\t}\n\t\t\t\t\t// Handle numeric comparison\n\t\t\t\t\telse if (typeof aValue === \"number\" && typeof bValue === \"number\") {\n\t\t\t\t\t\tcomparison = aValue - bValue;\n\t\t\t\t\t}\n\t\t\t\t\t// Handle boolean comparison\n\t\t\t\t\telse if (typeof aValue === \"boolean\" && typeof bValue === \"boolean\") {\n\t\t\t\t\t\tcomparison = aValue === bValue ? 0 : aValue ? 1 : -1;\n\t\t\t\t\t}\n\t\t\t\t\t// Fallback to string comparison\n\t\t\t\t\telse {\n\t\t\t\t\t\tcomparison = String(aValue).localeCompare(String(bValue));\n\t\t\t\t\t}\n\n\t\t\t\t\treturn sortBy.direction === \"asc\" ? comparison : -comparison;\n\t\t\t\t});\n\t\t\t};\n\n\t\t\tfunction convertWhereClause(\n\t\t\t\twhere: CleanedWhere[],\n\t\t\t\tmodel: string,\n\t\t\t\tjoin?: JoinConfig,\n\t\t\t): any[] {\n\t\t\t\tconst execute = (where: CleanedWhere[], model: string) => {\n\t\t\t\t\tconst table = db[model];\n\t\t\t\t\tif (!table) {\n\t\t\t\t\t\tlogger.error(\n\t\t\t\t\t\t\t`[MemoryAdapter] Model ${model} not found in the DB`,\n\t\t\t\t\t\t\tObject.keys(db),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tthrow new Error(`Model ${model} not found`);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst evalClause = (record: any, clause: CleanedWhere): boolean => {\n\t\t\t\t\t\tconst { field, value, operator } = clause;\n\t\t\t\t\t\tswitch (operator) {\n\t\t\t\t\t\t\tcase \"in\":\n\t\t\t\t\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Value must be an array\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\treturn value.includes(record[field]);\n\t\t\t\t\t\t\tcase \"not_in\":\n\t\t\t\t\t\t\t\tif (!Array.isArray(value)) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Value must be an array\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\t\t\treturn !value.includes(record[field]);\n\t\t\t\t\t\t\tcase \"contains\":\n\t\t\t\t\t\t\t\treturn record[field].includes(value);\n\t\t\t\t\t\t\tcase \"starts_with\":\n\t\t\t\t\t\t\t\treturn record[field].startsWith(value);\n\t\t\t\t\t\t\tcase \"ends_with\":\n\t\t\t\t\t\t\t\treturn record[field].endsWith(value);\n\t\t\t\t\t\t\tcase \"ne\":\n\t\t\t\t\t\t\t\treturn record[field] !== value;\n\t\t\t\t\t\t\tcase \"gt\":\n\t\t\t\t\t\t\t\treturn value != null && Boolean(record[field] > value);\n\t\t\t\t\t\t\tcase \"gte\":\n\t\t\t\t\t\t\t\treturn value != null && Boolean(record[field] >= value);\n\t\t\t\t\t\t\tcase \"lt\":\n\t\t\t\t\t\t\t\treturn value != null && Boolean(record[field] < value);\n\t\t\t\t\t\t\tcase \"lte\":\n\t\t\t\t\t\t\t\treturn value != null && Boolean(record[field] <= value);\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\treturn record[field] === value;\n\t\t\t\t\t\t}\n\t\t\t\t\t};\n\n\t\t\t\t\treturn table.filter((record: any) => {\n\t\t\t\t\t\tif (!where.length || where.length === 0) {\n\t\t\t\t\t\t\treturn true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlet result = evalClause(record, where[0]!);\n\t\t\t\t\t\tfor (const clause of where) {\n\t\t\t\t\t\t\tconst clauseResult = evalClause(record, clause);\n\n\t\t\t\t\t\t\tif (clause.connector === \"OR\") {\n\t\t\t\t\t\t\t\tresult = result || clauseResult;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tresult = result && clauseResult;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t});\n\t\t\t\t};\n\n\t\t\t\tif (!join) return execute(where, model);\n\n\t\t\t\tconst baseRecords = execute(where, model);\n\n\t\t\t\t// Group results by base model and nest joined data as arrays\n\t\t\t\tconst grouped = new Map<string, any>();\n\t\t\t\t// Track seen IDs per joined model for O(1) deduplication\n\t\t\t\tconst seenIds = new Map<string, Set<string>>();\n\n\t\t\t\tfor (const baseRecord of baseRecords) {\n\t\t\t\t\tconst baseId = String(baseRecord.id);\n\n\t\t\t\t\tif (!grouped.has(baseId)) {\n\t\t\t\t\t\tconst nested: Record<string, any> = { ...baseRecord };\n\n\t\t\t\t\t\t// Initialize joined data structures based on isUnique\n\t\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\t\t\tif (joinAttr.relation === \"one-to-one\") {\n\t\t\t\t\t\t\t\tnested[joinModelName] = null;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tnested[joinModelName] = [];\n\t\t\t\t\t\t\t\tseenIds.set(`${baseId}-${joinModel}`, new Set());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tgrouped.set(baseId, nested);\n\t\t\t\t\t}\n\n\t\t\t\t\tconst nestedEntry = grouped.get(baseId)!;\n\n\t\t\t\t\t// Add joined data\n\t\t\t\t\tfor (const [joinModel, joinAttr] of Object.entries(join)) {\n\t\t\t\t\t\tconst joinModelName = getModelName(joinModel);\n\t\t\t\t\t\tconst joinTable = db[joinModelName];\n\t\t\t\t\t\tif (!joinTable) {\n\t\t\t\t\t\t\tlogger.error(\n\t\t\t\t\t\t\t\t`[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`,\n\t\t\t\t\t\t\t\tObject.keys(db),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tthrow new Error(`JoinOption model ${joinModelName} not found`);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst matchingRecords = joinTable.filter(\n\t\t\t\t\t\t\t(joinRecord: any) =>\n\t\t\t\t\t\t\t\tjoinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from],\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (joinAttr.relation === \"one-to-one\") {\n\t\t\t\t\t\t\t// For unique relationships, store a single object (or null)\n\t\t\t\t\t\t\tnestedEntry[joinModelName] = matchingRecords[0] || null;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// For non-unique relationships, store array with limit\n\t\t\t\t\t\t\tconst seenSet = seenIds.get(`${baseId}-${joinModel}`)!;\n\t\t\t\t\t\t\tconst limit = joinAttr.limit ?? 100;\n\t\t\t\t\t\t\tlet count = 0;\n\n\t\t\t\t\t\t\tfor (const matchingRecord of matchingRecords) {\n\t\t\t\t\t\t\t\tif (count >= limit) break;\n\t\t\t\t\t\t\t\tif (!seenSet.has(matchingRecord.id)) {\n\t\t\t\t\t\t\t\t\tnestedEntry[joinModelName].push(matchingRecord);\n\t\t\t\t\t\t\t\t\tseenSet.add(matchingRecord.id);\n\t\t\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn Array.from(grouped.values());\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcreate: async ({ model, data }) => {\n\t\t\t\t\tconst useNumberId =\n\t\t\t\t\t\toptions.advanced?.database?.useNumberId ||\n\t\t\t\t\t\toptions.advanced?.database?.generateId === \"serial\";\n\t\t\t\t\tif (useNumberId) {\n\t\t\t\t\t\t// @ts-expect-error\n\t\t\t\t\t\tdata.id = db[getModelName(model)]!.length + 1;\n\t\t\t\t\t}\n\t\t\t\t\tif (!db[model]) {\n\t\t\t\t\t\tdb[model] = [];\n\t\t\t\t\t}\n\t\t\t\t\tdb[model]!.push(data);\n\t\t\t\t\treturn data;\n\t\t\t\t},\n\t\t\t\tfindOne: async ({ model, where, join }) => {\n\t\t\t\t\tconst res = convertWhereClause(where, model, join);\n\t\t\t\t\tif (join) {\n\t\t\t\t\t\t// When join is present, res is an array of nested objects\n\t\t\t\t\t\tconst resArray = res as any[];\n\t\t\t\t\t\tif (!resArray.length) {\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Return the first nested object\n\t\t\t\t\t\treturn resArray[0];\n\t\t\t\t\t}\n\t\t\t\t\t// Without join, res is an array\n\t\t\t\t\tconst resArray = res as any[];\n\t\t\t\t\tconst record = resArray[0] || null;\n\t\t\t\t\treturn record;\n\t\t\t\t},\n\t\t\t\tfindMany: async ({ model, where, sortBy, limit, offset, join }) => {\n\t\t\t\t\tconst res = convertWhereClause(where || [], model, join);\n\n\t\t\t\t\tif (join) {\n\t\t\t\t\t\t// When join is present, res is an array of nested objects\n\t\t\t\t\t\tconst resArray = res as any[];\n\t\t\t\t\t\tif (!resArray.length) {\n\t\t\t\t\t\t\treturn [];\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Apply sorting to nested objects\n\t\t\t\t\t\tapplySortToRecords(resArray, sortBy, model);\n\n\t\t\t\t\t\t// Apply offset and limit\n\t\t\t\t\t\tlet paginatedRecords = resArray;\n\t\t\t\t\t\tif (offset !== undefined) {\n\t\t\t\t\t\t\tpaginatedRecords = paginatedRecords.slice(offset);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\t\tpaginatedRecords = paginatedRecords.slice(0, limit);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn paginatedRecords;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Without join - original logic\n\t\t\t\t\tconst resArray = res as any[];\n\t\t\t\t\tlet table = applySortToRecords(resArray, sortBy, model);\n\t\t\t\t\tif (offset !== undefined) {\n\t\t\t\t\t\ttable = table!.slice(offset);\n\t\t\t\t\t}\n\t\t\t\t\tif (limit !== undefined) {\n\t\t\t\t\t\ttable = table!.slice(0, limit);\n\t\t\t\t\t}\n\t\t\t\t\treturn table || [];\n\t\t\t\t},\n\t\t\t\tcount: async ({ model, where }) => {\n\t\t\t\t\tif (where) {\n\t\t\t\t\t\tconst filteredRecords = convertWhereClause(where, model);\n\t\t\t\t\t\treturn filteredRecords.length;\n\t\t\t\t\t}\n\t\t\t\t\treturn db[model]!.length;\n\t\t\t\t},\n\t\t\t\tupdate: async ({ model, where, update }) => {\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tres.forEach((record) => {\n\t\t\t\t\t\tObject.assign(record, update);\n\t\t\t\t\t});\n\t\t\t\t\treturn res[0] || null;\n\t\t\t\t},\n\t\t\t\tdelete: async ({ model, where }) => {\n\t\t\t\t\tconst table = db[model]!;\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tdb[model] = table.filter((record) => !res.includes(record));\n\t\t\t\t},\n\t\t\t\tdeleteMany: async ({ model, where }) => {\n\t\t\t\t\tconst table = db[model]!;\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tlet count = 0;\n\t\t\t\t\tdb[model] = table.filter((record) => {\n\t\t\t\t\t\tif (res.includes(record)) {\n\t\t\t\t\t\t\tcount++;\n\t\t\t\t\t\t\treturn false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn !res.includes(record);\n\t\t\t\t\t});\n\t\t\t\t\treturn count;\n\t\t\t\t},\n\t\t\t\tupdateMany({ model, where, update }) {\n\t\t\t\t\tconst res = convertWhereClause(where, model);\n\t\t\t\t\tres.forEach((record) => {\n\t\t\t\t\t\tObject.assign(record, update);\n\t\t\t\t\t});\n\t\t\t\t\treturn res[0] || null;\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t});\n\treturn (options: BetterAuthOptions) => {\n\t\tlazyOptions = options;\n\t\treturn adapterCreator(options);\n\t};\n};\n"],"mappings":";;;;AAiBA,MAAa,iBACZ,IACA,WACI;CACJ,IAAI,cAAwC;CAC5C,MAAM,iBAAiB,qBAAqB;EAC3C,QAAQ;GACP,WAAW;GACX,aAAa;GACb,WAAW;GACX,WAAW,QAAQ,aAAa;GAChC,gBAAgB;GAChB,qBAAqB,OAAO;AAI3B,SAFC,MAAM,QAAQ,UAAU,UAAU,eAClC,MAAM,QAAQ,UAAU,UAAU,eAAe,aAC/B,MAAM,UAAU,QAAQ,MAAM,WAAW,SAC3D,QAAO,GAAG,MAAM,OAAQ,SAAS;AAElC,WAAO,MAAM;;GAEd,aAAa,OAAO,OAAO;IAC1B,MAAM,QAAQ,gBAAgB,GAAG;AACjC,QAAI;AAEH,YADU,MAAM,GAAG,eAAe,YAAa,CAAC;aAExC,OAAO;AAEf,YAAO,KAAK,GAAG,CAAC,SAAS,QAAQ;AAChC,SAAG,OAAO,MAAM;OACf;AACF,WAAM;;;GAGR;EACD,UAAU,EAAE,cAAc,SAAS,mBAAmB;GACrD,MAAM,sBACL,SACA,QACA,UACI;AACJ,QAAI,CAAC,OAAQ,QAAO;AACpB,WAAO,QAAQ,MAAM,GAAQ,MAAW;KACvC,MAAM,QAAQ,aAAa;MAAE;MAAO,OAAO,OAAO;MAAO,CAAC;KAC1D,MAAM,SAAS,EAAE;KACjB,MAAM,SAAS,EAAE;KAEjB,IAAI,aAAa;AAGjB,SAAI,UAAU,QAAQ,UAAU,KAC/B,cAAa;cACH,UAAU,KACpB,cAAa;cACH,UAAU,KACpB,cAAa;cAGL,OAAO,WAAW,YAAY,OAAO,WAAW,SACxD,cAAa,OAAO,cAAc,OAAO;cAGjC,kBAAkB,QAAQ,kBAAkB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-0,0 +1,37 @@
1
+ {
2
+ "name": "@hammadj/better-auth-memory-adapter",
3
+ "version": "1.5.0-beta.9",
4
+ "description": "Memory adapter for Better Auth",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/META-DREAMER/better-auth.git",
9
+ "directory": "packages/memory-adapter"
10
+ },
11
+ "main": "./dist/index.mjs",
12
+ "module": "./dist/index.mjs",
13
+ "types": "./dist/index.d.mts",
14
+ "exports": {
15
+ ".": {
16
+ "dev-source": "./src/index.ts",
17
+ "types": "./dist/index.d.mts",
18
+ "default": "./dist/index.mjs"
19
+ }
20
+ },
21
+ "peerDependencies": {
22
+ "@better-auth/utils": "^0.3.0",
23
+ "@hammadj/better-auth-core": "1.5.0-beta.9"
24
+ },
25
+ "devDependencies": {
26
+ "@better-auth/utils": "^0.3.1",
27
+ "tsdown": "^0.20.1",
28
+ "typescript": "^5.9.3",
29
+ "@hammadj/better-auth-core": "1.5.0-beta.9"
30
+ },
31
+ "scripts": {
32
+ "build": "tsdown",
33
+ "dev": "tsdown --watch",
34
+ "test": "vitest",
35
+ "typecheck": "tsc --noEmit"
36
+ }
37
+ }
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export {
2
+ type MemoryAdapterConfig,
3
+ type MemoryDB,
4
+ memoryAdapter,
5
+ } from "./memory-adapter";
@@ -0,0 +1,355 @@
1
+ import type { BetterAuthOptions } from "@better-auth/core";
2
+ import type {
3
+ CleanedWhere,
4
+ DBAdapterDebugLogOption,
5
+ JoinConfig,
6
+ } from "@better-auth/core/db/adapter";
7
+ import { createAdapterFactory } from "@better-auth/core/db/adapter";
8
+ import { logger } from "@better-auth/core/env";
9
+
10
+ export interface MemoryDB {
11
+ [key: string]: any[];
12
+ }
13
+
14
+ export interface MemoryAdapterConfig {
15
+ debugLogs?: DBAdapterDebugLogOption | undefined;
16
+ }
17
+
18
+ export const memoryAdapter = (
19
+ db: MemoryDB,
20
+ config?: MemoryAdapterConfig | undefined,
21
+ ) => {
22
+ let lazyOptions: BetterAuthOptions | null = null;
23
+ const adapterCreator = createAdapterFactory({
24
+ config: {
25
+ adapterId: "memory",
26
+ adapterName: "Memory Adapter",
27
+ usePlural: false,
28
+ debugLogs: config?.debugLogs || false,
29
+ supportsArrays: true,
30
+ customTransformInput(props) {
31
+ const useNumberId =
32
+ props.options.advanced?.database?.useNumberId ||
33
+ props.options.advanced?.database?.generateId === "serial";
34
+ if (useNumberId && props.field === "id" && props.action === "create") {
35
+ return db[props.model]!.length + 1;
36
+ }
37
+ return props.data;
38
+ },
39
+ transaction: async (cb) => {
40
+ const clone = structuredClone(db);
41
+ try {
42
+ const r = await cb(adapterCreator(lazyOptions!));
43
+ return r;
44
+ } catch (error) {
45
+ // Rollback changes
46
+ Object.keys(db).forEach((key) => {
47
+ db[key] = clone[key]!;
48
+ });
49
+ throw error;
50
+ }
51
+ },
52
+ },
53
+ adapter: ({ getFieldName, options, getModelName }) => {
54
+ const applySortToRecords = (
55
+ records: any[],
56
+ sortBy: { field: string; direction: "asc" | "desc" } | undefined,
57
+ model: string,
58
+ ) => {
59
+ if (!sortBy) return records;
60
+ return records.sort((a: any, b: any) => {
61
+ const field = getFieldName({ model, field: sortBy.field });
62
+ const aValue = a[field];
63
+ const bValue = b[field];
64
+
65
+ let comparison = 0;
66
+
67
+ // Handle null/undefined values
68
+ if (aValue == null && bValue == null) {
69
+ comparison = 0;
70
+ } else if (aValue == null) {
71
+ comparison = -1;
72
+ } else if (bValue == null) {
73
+ comparison = 1;
74
+ }
75
+ // Handle string comparison
76
+ else if (typeof aValue === "string" && typeof bValue === "string") {
77
+ comparison = aValue.localeCompare(bValue);
78
+ }
79
+ // Handle date comparison
80
+ else if (aValue instanceof Date && bValue instanceof Date) {
81
+ comparison = aValue.getTime() - bValue.getTime();
82
+ }
83
+ // Handle numeric comparison
84
+ else if (typeof aValue === "number" && typeof bValue === "number") {
85
+ comparison = aValue - bValue;
86
+ }
87
+ // Handle boolean comparison
88
+ else if (typeof aValue === "boolean" && typeof bValue === "boolean") {
89
+ comparison = aValue === bValue ? 0 : aValue ? 1 : -1;
90
+ }
91
+ // Fallback to string comparison
92
+ else {
93
+ comparison = String(aValue).localeCompare(String(bValue));
94
+ }
95
+
96
+ return sortBy.direction === "asc" ? comparison : -comparison;
97
+ });
98
+ };
99
+
100
+ function convertWhereClause(
101
+ where: CleanedWhere[],
102
+ model: string,
103
+ join?: JoinConfig,
104
+ ): any[] {
105
+ const execute = (where: CleanedWhere[], model: string) => {
106
+ const table = db[model];
107
+ if (!table) {
108
+ logger.error(
109
+ `[MemoryAdapter] Model ${model} not found in the DB`,
110
+ Object.keys(db),
111
+ );
112
+ throw new Error(`Model ${model} not found`);
113
+ }
114
+
115
+ const evalClause = (record: any, clause: CleanedWhere): boolean => {
116
+ const { field, value, operator } = clause;
117
+ switch (operator) {
118
+ case "in":
119
+ if (!Array.isArray(value)) {
120
+ throw new Error("Value must be an array");
121
+ }
122
+ // @ts-expect-error
123
+ return value.includes(record[field]);
124
+ case "not_in":
125
+ if (!Array.isArray(value)) {
126
+ throw new Error("Value must be an array");
127
+ }
128
+ // @ts-expect-error
129
+ return !value.includes(record[field]);
130
+ case "contains":
131
+ return record[field].includes(value);
132
+ case "starts_with":
133
+ return record[field].startsWith(value);
134
+ case "ends_with":
135
+ return record[field].endsWith(value);
136
+ case "ne":
137
+ return record[field] !== value;
138
+ case "gt":
139
+ return value != null && Boolean(record[field] > value);
140
+ case "gte":
141
+ return value != null && Boolean(record[field] >= value);
142
+ case "lt":
143
+ return value != null && Boolean(record[field] < value);
144
+ case "lte":
145
+ return value != null && Boolean(record[field] <= value);
146
+ default:
147
+ return record[field] === value;
148
+ }
149
+ };
150
+
151
+ return table.filter((record: any) => {
152
+ if (!where.length || where.length === 0) {
153
+ return true;
154
+ }
155
+
156
+ let result = evalClause(record, where[0]!);
157
+ for (const clause of where) {
158
+ const clauseResult = evalClause(record, clause);
159
+
160
+ if (clause.connector === "OR") {
161
+ result = result || clauseResult;
162
+ } else {
163
+ result = result && clauseResult;
164
+ }
165
+ }
166
+
167
+ return result;
168
+ });
169
+ };
170
+
171
+ if (!join) return execute(where, model);
172
+
173
+ const baseRecords = execute(where, model);
174
+
175
+ // Group results by base model and nest joined data as arrays
176
+ const grouped = new Map<string, any>();
177
+ // Track seen IDs per joined model for O(1) deduplication
178
+ const seenIds = new Map<string, Set<string>>();
179
+
180
+ for (const baseRecord of baseRecords) {
181
+ const baseId = String(baseRecord.id);
182
+
183
+ if (!grouped.has(baseId)) {
184
+ const nested: Record<string, any> = { ...baseRecord };
185
+
186
+ // Initialize joined data structures based on isUnique
187
+ for (const [joinModel, joinAttr] of Object.entries(join)) {
188
+ const joinModelName = getModelName(joinModel);
189
+ if (joinAttr.relation === "one-to-one") {
190
+ nested[joinModelName] = null;
191
+ } else {
192
+ nested[joinModelName] = [];
193
+ seenIds.set(`${baseId}-${joinModel}`, new Set());
194
+ }
195
+ }
196
+
197
+ grouped.set(baseId, nested);
198
+ }
199
+
200
+ const nestedEntry = grouped.get(baseId)!;
201
+
202
+ // Add joined data
203
+ for (const [joinModel, joinAttr] of Object.entries(join)) {
204
+ const joinModelName = getModelName(joinModel);
205
+ const joinTable = db[joinModelName];
206
+ if (!joinTable) {
207
+ logger.error(
208
+ `[MemoryAdapter] JoinOption model ${joinModelName} not found in the DB`,
209
+ Object.keys(db),
210
+ );
211
+ throw new Error(`JoinOption model ${joinModelName} not found`);
212
+ }
213
+
214
+ const matchingRecords = joinTable.filter(
215
+ (joinRecord: any) =>
216
+ joinRecord[joinAttr.on.to] === baseRecord[joinAttr.on.from],
217
+ );
218
+
219
+ if (joinAttr.relation === "one-to-one") {
220
+ // For unique relationships, store a single object (or null)
221
+ nestedEntry[joinModelName] = matchingRecords[0] || null;
222
+ } else {
223
+ // For non-unique relationships, store array with limit
224
+ const seenSet = seenIds.get(`${baseId}-${joinModel}`)!;
225
+ const limit = joinAttr.limit ?? 100;
226
+ let count = 0;
227
+
228
+ for (const matchingRecord of matchingRecords) {
229
+ if (count >= limit) break;
230
+ if (!seenSet.has(matchingRecord.id)) {
231
+ nestedEntry[joinModelName].push(matchingRecord);
232
+ seenSet.add(matchingRecord.id);
233
+ count++;
234
+ }
235
+ }
236
+ }
237
+ }
238
+ }
239
+
240
+ return Array.from(grouped.values());
241
+ }
242
+ return {
243
+ create: async ({ model, data }) => {
244
+ const useNumberId =
245
+ options.advanced?.database?.useNumberId ||
246
+ options.advanced?.database?.generateId === "serial";
247
+ if (useNumberId) {
248
+ // @ts-expect-error
249
+ data.id = db[getModelName(model)]!.length + 1;
250
+ }
251
+ if (!db[model]) {
252
+ db[model] = [];
253
+ }
254
+ db[model]!.push(data);
255
+ return data;
256
+ },
257
+ findOne: async ({ model, where, join }) => {
258
+ const res = convertWhereClause(where, model, join);
259
+ if (join) {
260
+ // When join is present, res is an array of nested objects
261
+ const resArray = res as any[];
262
+ if (!resArray.length) {
263
+ return null;
264
+ }
265
+ // Return the first nested object
266
+ return resArray[0];
267
+ }
268
+ // Without join, res is an array
269
+ const resArray = res as any[];
270
+ const record = resArray[0] || null;
271
+ return record;
272
+ },
273
+ findMany: async ({ model, where, sortBy, limit, offset, join }) => {
274
+ const res = convertWhereClause(where || [], model, join);
275
+
276
+ if (join) {
277
+ // When join is present, res is an array of nested objects
278
+ const resArray = res as any[];
279
+ if (!resArray.length) {
280
+ return [];
281
+ }
282
+
283
+ // Apply sorting to nested objects
284
+ applySortToRecords(resArray, sortBy, model);
285
+
286
+ // Apply offset and limit
287
+ let paginatedRecords = resArray;
288
+ if (offset !== undefined) {
289
+ paginatedRecords = paginatedRecords.slice(offset);
290
+ }
291
+ if (limit !== undefined) {
292
+ paginatedRecords = paginatedRecords.slice(0, limit);
293
+ }
294
+
295
+ return paginatedRecords;
296
+ }
297
+
298
+ // Without join - original logic
299
+ const resArray = res as any[];
300
+ let table = applySortToRecords(resArray, sortBy, model);
301
+ if (offset !== undefined) {
302
+ table = table!.slice(offset);
303
+ }
304
+ if (limit !== undefined) {
305
+ table = table!.slice(0, limit);
306
+ }
307
+ return table || [];
308
+ },
309
+ count: async ({ model, where }) => {
310
+ if (where) {
311
+ const filteredRecords = convertWhereClause(where, model);
312
+ return filteredRecords.length;
313
+ }
314
+ return db[model]!.length;
315
+ },
316
+ update: async ({ model, where, update }) => {
317
+ const res = convertWhereClause(where, model);
318
+ res.forEach((record) => {
319
+ Object.assign(record, update);
320
+ });
321
+ return res[0] || null;
322
+ },
323
+ delete: async ({ model, where }) => {
324
+ const table = db[model]!;
325
+ const res = convertWhereClause(where, model);
326
+ db[model] = table.filter((record) => !res.includes(record));
327
+ },
328
+ deleteMany: async ({ model, where }) => {
329
+ const table = db[model]!;
330
+ const res = convertWhereClause(where, model);
331
+ let count = 0;
332
+ db[model] = table.filter((record) => {
333
+ if (res.includes(record)) {
334
+ count++;
335
+ return false;
336
+ }
337
+ return !res.includes(record);
338
+ });
339
+ return count;
340
+ },
341
+ updateMany({ model, where, update }) {
342
+ const res = convertWhereClause(where, model);
343
+ res.forEach((record) => {
344
+ Object.assign(record, update);
345
+ });
346
+ return res[0] || null;
347
+ },
348
+ };
349
+ },
350
+ });
351
+ return (options: BetterAuthOptions) => {
352
+ lazyOptions = options;
353
+ return adapterCreator(options);
354
+ };
355
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "include": ["./src"],
4
+ "references": [
5
+ {
6
+ "path": "../core/tsconfig.json"
7
+ }
8
+ ]
9
+ }
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from "tsdown";
2
+
3
+ export default defineConfig({
4
+ dts: { build: true, incremental: true },
5
+ format: ["esm"],
6
+ entry: ["./src/index.ts"],
7
+ sourcemap: true,
8
+ });
@@ -0,0 +1,3 @@
1
+ import { defineProject } from "vitest/config";
2
+
3
+ export default defineProject({});