@topgunbuild/adapter-better-auth 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,97 @@
1
+ Business Source License 1.1
2
+
3
+ Parameters
4
+
5
+ Licensor: TopGun Contributors
6
+ Licensed Work: TopGun
7
+ The Licensed Work is (c) 2024 TopGun Contributors.
8
+ Additional Use Grant: You may make production use of the Licensed Work,
9
+ provided Your use does not include offering the
10
+ Licensed Work to third parties as a commercial
11
+ managed database service, database-as-a-service,
12
+ or similar hosted database offering that competes
13
+ with TopGun products or services.
14
+
15
+ For purposes of this license:
16
+ - "Managed database service" means a service that
17
+ allows third parties to create, manage, or operate
18
+ databases using TopGun as the underlying technology.
19
+ - Internal use within your organization is permitted.
20
+ - Using TopGun as part of your application's backend
21
+ (not exposed as a database service) is permitted.
22
+ - Consulting and professional services around TopGun
23
+ are permitted.
24
+
25
+ Change Date: Four years from the date of each version release
26
+ Change License: Apache License, Version 2.0
27
+
28
+ For information about alternative licensing arrangements for the Licensed Work,
29
+ please contact the Licensor.
30
+
31
+ Notice
32
+
33
+ Business Source License 1.1
34
+
35
+ Terms
36
+
37
+ The Licensor hereby grants you the right to copy, modify, create derivative
38
+ works, redistribute, and make non-production use of the Licensed Work. The
39
+ Licensor may make an Additional Use Grant, above, permitting limited production use.
40
+
41
+ Effective on the Change Date, or the fourth anniversary of the first publicly
42
+ available distribution of a specific version of the Licensed Work under this
43
+ License, whichever comes first, the Licensor hereby grants you rights under
44
+ the terms of the Change License, and the rights granted in the paragraph
45
+ above terminate.
46
+
47
+ If your use of the Licensed Work does not comply with the requirements
48
+ currently in effect as described in this License, you must purchase a
49
+ commercial license from the Licensor, its affiliated entities, or authorized
50
+ resellers, or you must refrain from using the Licensed Work.
51
+
52
+ All copies of the original and modified Licensed Work, and derivative works
53
+ of the Licensed Work, are subject to this License. This License applies
54
+ separately for each version of the Licensed Work and the Change Date may vary
55
+ for each version of the Licensed Work released by Licensor.
56
+
57
+ You must conspicuously display this License on each original or modified copy
58
+ of the Licensed Work. If you receive the Licensed Work in original or
59
+ modified form from a third party, the terms and conditions set forth in this
60
+ License apply to your use of that work.
61
+
62
+ Any use of the Licensed Work in violation of this License will automatically
63
+ terminate your rights under this License for the current and all other
64
+ versions of the Licensed Work.
65
+
66
+ This License does not grant you any right in any trademark or logo of
67
+ Licensor or its affiliates (provided that you may use a trademark or logo of
68
+ Licensor as expressly required by this License).
69
+
70
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
71
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
72
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
73
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
74
+ TITLE.
75
+
76
+ MariaDB hereby grants you permission to use this License's text to license
77
+ your works, and to refer to it using the trademark "Business Source License",
78
+ as long as you comply with the Covenants of Licensor below.
79
+
80
+ Covenants of Licensor
81
+
82
+ In consideration of the right to use this License's text and the "Business
83
+ Source License" name and trademark, Licensor covenants to MariaDB, and to all
84
+ other recipients of the licensed work to be provided by Licensor:
85
+
86
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
87
+ or a license that is compatible with GPL Version 2.0 or a later version,
88
+ where "compatible" means that software provided under the Change License can
89
+ be included in a program with software provided under GPL Version 2.0 or a
90
+ later version. Licensor may specify additional Change Licenses without
91
+ limitation.
92
+
93
+ 2. To either: (a) specify an Additional Use Grant (above) that does not impose
94
+ any additional restriction on the right granted in this License, as the
95
+ Additional Use Grant; or (b) insert the text "None" to specify a Change Date.
96
+
97
+ 3. Not to modify this License in any other way.
package/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # @topgunbuild/adapter-better-auth
2
+
3
+ Better Auth adapter for TopGun - a local-first, real-time database sync engine.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @topgunbuild/adapter-better-auth
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { betterAuth } from "better-auth";
15
+ import { topGunAdapter } from "@topgunbuild/adapter-better-auth";
16
+ import { TopGunClient } from "@topgunbuild/client";
17
+
18
+ const client = new TopGunClient({
19
+ serverUrl: "ws://localhost:4000",
20
+ // ... options
21
+ });
22
+
23
+ await client.start();
24
+
25
+ export const auth = betterAuth({
26
+ database: topGunAdapter({
27
+ client,
28
+ modelMap: {
29
+ user: "users",
30
+ session: "sessions",
31
+ account: "accounts",
32
+ verification: "verifications"
33
+ }
34
+ }),
35
+ // ... other better-auth options
36
+ });
37
+ ```
38
+
39
+ ## Limitations
40
+
41
+ ### Transactions
42
+
43
+ TopGun is a distributed, eventually consistent system based on CRDTs. It does not support traditional ACID transactions spanning multiple maps/tables.
44
+
45
+ The `transaction` method in this adapter executes operations sequentially. While this works for typical authentication flows (like creating a User and an Account), strict atomicity is not guaranteed in case of a crash or network partition between operations.
46
+
47
+ - **Consistency**: Eventual.
48
+ - **Atomicity**: Partial (operations are applied one by one).
49
+ - **Isolation**: None (updates are immediately visible locally).
50
+
51
+ ### Cold Start
52
+
53
+ When the application starts, the adapter might need to wait for local data to be loaded from storage. The adapter handles this by using reactive queries for `findOne`, ensuring data availability before returning.
54
+
@@ -0,0 +1,14 @@
1
+ import { TopGunClient } from '@topgunbuild/client';
2
+ import { DBAdapterInstance } from 'better-auth/adapters';
3
+
4
+ interface TopGunAdapterOptions {
5
+ client: TopGunClient;
6
+ /**
7
+ * Map model names to TopGun map names.
8
+ * Default: "auth_user", "auth_session", etc.
9
+ */
10
+ modelMap?: Record<string, string>;
11
+ }
12
+ declare const topGunAdapter: (adapterOptions: TopGunAdapterOptions) => DBAdapterInstance;
13
+
14
+ export { type TopGunAdapterOptions, topGunAdapter };
@@ -0,0 +1,14 @@
1
+ import { TopGunClient } from '@topgunbuild/client';
2
+ import { DBAdapterInstance } from 'better-auth/adapters';
3
+
4
+ interface TopGunAdapterOptions {
5
+ client: TopGunClient;
6
+ /**
7
+ * Map model names to TopGun map names.
8
+ * Default: "auth_user", "auth_session", etc.
9
+ */
10
+ modelMap?: Record<string, string>;
11
+ }
12
+ declare const topGunAdapter: (adapterOptions: TopGunAdapterOptions) => DBAdapterInstance;
13
+
14
+ export { type TopGunAdapterOptions, topGunAdapter };
package/dist/index.js ADDED
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ topGunAdapter: () => topGunAdapter
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/TopGunAdapter.ts
28
+ var import_client = require("@topgunbuild/client");
29
+ var topGunAdapter = (adapterOptions) => {
30
+ return (options) => {
31
+ const { client, modelMap = {} } = adapterOptions;
32
+ const getMapName = (model) => {
33
+ return modelMap[model] || `auth_${model}`;
34
+ };
35
+ const whereToPredicate = (where) => {
36
+ if (!where || where.length === 0) return void 0;
37
+ const predicates = where.map((w) => {
38
+ const field = w.field;
39
+ const value = w.value;
40
+ switch (w.operator) {
41
+ case "eq":
42
+ return import_client.Predicates.equal(field, value);
43
+ case "ne":
44
+ return import_client.Predicates.notEqual(field, value);
45
+ case "lt":
46
+ return import_client.Predicates.lessThan(field, value);
47
+ case "lte":
48
+ return import_client.Predicates.lessThanOrEqual(field, value);
49
+ case "gt":
50
+ return import_client.Predicates.greaterThan(field, value);
51
+ case "gte":
52
+ return import_client.Predicates.greaterThanOrEqual(field, value);
53
+ case "contains":
54
+ return import_client.Predicates.like(field, `%${value}%`);
55
+ case "starts_with":
56
+ return import_client.Predicates.like(field, `${value}%`);
57
+ case "ends_with":
58
+ return import_client.Predicates.like(field, `%${value}`);
59
+ case "in":
60
+ if (Array.isArray(value)) {
61
+ return import_client.Predicates.or(...value.map((v) => import_client.Predicates.equal(field, v)));
62
+ }
63
+ return import_client.Predicates.equal(field, value);
64
+ case "not_in":
65
+ if (Array.isArray(value)) {
66
+ return import_client.Predicates.and(...value.map((v) => import_client.Predicates.notEqual(field, v)));
67
+ }
68
+ return import_client.Predicates.notEqual(field, value);
69
+ default:
70
+ return import_client.Predicates.equal(field, value);
71
+ }
72
+ });
73
+ if (predicates.length === 1) return predicates[0];
74
+ return import_client.Predicates.and(...predicates);
75
+ };
76
+ const runQuery = async (model, where, sort, limit, offset) => {
77
+ const mapName = getMapName(model);
78
+ const predicate = where ? whereToPredicate(where) : void 0;
79
+ const filter = {
80
+ predicate,
81
+ sort,
82
+ limit,
83
+ offset
84
+ };
85
+ return new Promise((resolve) => {
86
+ const handle = client.query(mapName, filter);
87
+ const unsubscribe = handle.subscribe((results) => {
88
+ unsubscribe();
89
+ resolve(results);
90
+ });
91
+ });
92
+ };
93
+ return {
94
+ id: "topgun-adapter",
95
+ async create({ model, data }) {
96
+ const mapName = getMapName(model);
97
+ const id = data.id || crypto.randomUUID();
98
+ const record = { ...data, id };
99
+ const map = client.getMap(mapName);
100
+ map.set(id, record);
101
+ return record;
102
+ },
103
+ async findOne({ model, where, select, join }) {
104
+ const idCheck = where.find((w) => w.field === "id" && (w.operator === "eq" || w.operator === void 0));
105
+ if (idCheck && where.length === 1) {
106
+ const mapName = getMapName(model);
107
+ const map = client.getMap(mapName);
108
+ }
109
+ const results = await runQuery(model, where, void 0, 1);
110
+ if (results.length > 0) {
111
+ const result = results[0];
112
+ if (join) {
113
+ for (const [joinModel, joinConfig] of Object.entries(join)) {
114
+ if (joinConfig === false) continue;
115
+ const joinWhere = [{ field: "userId", value: result.id }];
116
+ const limit = typeof joinConfig === "object" ? joinConfig.limit : void 0;
117
+ const joinResults = await runQuery(joinModel, joinWhere, void 0, limit);
118
+ const pluralName = joinModel.endsWith("s") ? joinModel : joinModel + "s";
119
+ result[pluralName] = joinResults;
120
+ }
121
+ }
122
+ const fixDates = (obj) => {
123
+ if (!obj) return obj;
124
+ for (const key in obj) {
125
+ if (typeof obj[key] === "string" && /^\d{4}-\d{2}-\d{2}T/.test(obj[key])) {
126
+ obj[key] = new Date(obj[key]);
127
+ } else if (typeof obj[key] === "object" && obj[key] !== null) {
128
+ if (Array.isArray(obj[key])) {
129
+ obj[key].forEach((item) => fixDates(item));
130
+ }
131
+ }
132
+ }
133
+ return obj;
134
+ };
135
+ fixDates(result);
136
+ if (select) {
137
+ const selected = {};
138
+ select.forEach((field) => selected[field] = result[field]);
139
+ if (join) {
140
+ for (const joinModel of Object.keys(join)) {
141
+ const propName = joinModel.endsWith("s") ? joinModel : joinModel + "s";
142
+ if (result[propName]) {
143
+ selected[propName] = result[propName];
144
+ }
145
+ }
146
+ }
147
+ return selected;
148
+ }
149
+ return result;
150
+ }
151
+ return null;
152
+ },
153
+ async findMany({ model, where, limit, offset, sortBy }) {
154
+ const results = await runQuery(model, where, sortBy ? { [sortBy.field]: sortBy.direction } : void 0, limit, offset);
155
+ return results;
156
+ },
157
+ async update({ model, where, update }) {
158
+ const results = await runQuery(model, where);
159
+ if (results.length === 0) return null;
160
+ const mapName = getMapName(model);
161
+ const map = client.getMap(mapName);
162
+ const item = results[0];
163
+ const updatedItem = { ...item, ...update };
164
+ map.set(item.id, updatedItem);
165
+ return updatedItem;
166
+ },
167
+ async updateMany({ model, where, update }) {
168
+ const results = await runQuery(model, where);
169
+ const mapName = getMapName(model);
170
+ const map = client.getMap(mapName);
171
+ for (const item of results) {
172
+ map.set(item.id, { ...item, ...update });
173
+ }
174
+ return results.length;
175
+ },
176
+ async delete({ model, where }) {
177
+ const results = await runQuery(model, where);
178
+ const mapName = getMapName(model);
179
+ const map = client.getMap(mapName);
180
+ if (results.length > 0) {
181
+ map.remove(results[0].id);
182
+ }
183
+ },
184
+ async deleteMany({ model, where }) {
185
+ const results = await runQuery(model, where);
186
+ const mapName = getMapName(model);
187
+ const map = client.getMap(mapName);
188
+ for (const item of results) {
189
+ map.remove(item.id);
190
+ }
191
+ return results.length;
192
+ },
193
+ async count({ model, where }) {
194
+ const results = await runQuery(model, where);
195
+ return results.length;
196
+ },
197
+ async transaction(callback) {
198
+ return callback(this);
199
+ }
200
+ };
201
+ };
202
+ };
203
+ // Annotate the CommonJS export names for ESM import in node:
204
+ 0 && (module.exports = {
205
+ topGunAdapter
206
+ });
207
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/TopGunAdapter.ts"],"sourcesContent":["export * from './TopGunAdapter';\n\n","import { TopGunClient, Predicates } from '@topgunbuild/client';\nimport type { BetterAuthOptions } from 'better-auth';\nimport type { \n DBAdapter, \n Where,\n DBAdapterInstance\n} from 'better-auth/adapters';\nimport type { PredicateNode } from '@topgunbuild/core';\n\nexport interface TopGunAdapterOptions {\n client: TopGunClient;\n /**\n * Map model names to TopGun map names.\n * Default: \"auth_user\", \"auth_session\", etc.\n */\n modelMap?: Record<string, string>;\n}\n\nexport const topGunAdapter = (adapterOptions: TopGunAdapterOptions): DBAdapterInstance => {\n return (options: BetterAuthOptions): DBAdapter => {\n const { client, modelMap = {} } = adapterOptions;\n\n const getMapName = (model: string) => {\n return modelMap[model] || `auth_${model}`;\n };\n\n const whereToPredicate = (where: Where[]): PredicateNode | undefined => {\n if (!where || where.length === 0) return undefined;\n\n const predicates: PredicateNode[] = where.map(w => {\n const field = w.field;\n const value = w.value;\n \n switch (w.operator) {\n case 'eq': return Predicates.equal(field, value);\n case 'ne': return Predicates.notEqual(field, value);\n case 'lt': return Predicates.lessThan(field, value);\n case 'lte': return Predicates.lessThanOrEqual(field, value);\n case 'gt': return Predicates.greaterThan(field, value);\n case 'gte': return Predicates.greaterThanOrEqual(field, value);\n case 'contains': return Predicates.like(field, `%${value}%`);\n case 'starts_with': return Predicates.like(field, `${value}%`);\n case 'ends_with': return Predicates.like(field, `%${value}`);\n case 'in': \n if (Array.isArray(value)) {\n return Predicates.or(...value.map(v => Predicates.equal(field, v)));\n }\n return Predicates.equal(field, value);\n case 'not_in':\n if (Array.isArray(value)) {\n return Predicates.and(...value.map(v => Predicates.notEqual(field, v)));\n }\n return Predicates.notEqual(field, value);\n default: return Predicates.equal(field, value);\n }\n });\n\n // BetterAuth Where[] implies AND\n if (predicates.length === 1) return predicates[0];\n return Predicates.and(...predicates);\n };\n\n const runQuery = async <T>(model: string, where?: Where[], sort?: any, limit?: number, offset?: number): Promise<T[]> => {\n const mapName = getMapName(model);\n const predicate = where ? whereToPredicate(where) : undefined;\n \n const filter = {\n predicate,\n sort,\n limit,\n offset\n };\n\n // We use client.query which subscribes. We wait for the first result.\n // TopGun QueryHandle is reactive. We need a one-shot fetch.\n \n return new Promise((resolve) => {\n const handle = client.query<T>(mapName, filter);\n \n // Subscribe returns an unsubscribe function\n const unsubscribe = handle.subscribe((results: T[]) => {\n unsubscribe();\n resolve(results);\n });\n });\n };\n\n return {\n id: 'topgun-adapter',\n \n async create({ model, data }) {\n const mapName = getMapName(model);\n const id = (data as any).id || crypto.randomUUID();\n const record = { ...data, id };\n \n // Use LWWMap for standard records\n const map = client.getMap<string, any>(mapName);\n map.set(id, record);\n \n // map.set is optimistic and writes to local storage/sync engine.\n // Ideally we wait for confirmation? TopGun doesn't expose Promise for set completion easily \n // (it returns the record). But SyncEngine queues it.\n \n return record as any;\n },\n\n async findOne({ model, where, select, join }) {\n // Optimization: If where is just ID check, use getMap().get()\n const idCheck = where.find(w => w.field === 'id' && (w.operator === 'eq' || w.operator === undefined));\n if (idCheck && where.length === 1) {\n const mapName = getMapName(model);\n const map = client.getMap<string, any>(mapName);\n // LWWMap.get is synchronous from memory (loaded from storage).\n // If we haven't loaded yet, we might miss it.\n // Ideally we should ensure map is loaded.\n // TopGunClient.getMap returns immediately but starts restoring in background.\n // This creates a race condition for cold start.\n \n // Workaround: Use runQuery which waits for initial load via QueryHandle -> loadInitialLocalData\n // But for simple ID, query is overkill?\n // Let's use runQuery to be safe and consistent.\n }\n\n const results = await runQuery<any>(model, where, undefined, 1);\n \n if (results.length > 0) {\n const result = results[0];\n\n // Handle Join\n if (join) {\n for (const [joinModel, joinConfig] of Object.entries(join)) {\n if (joinConfig === false) continue;\n \n // Assume standard relation on userId\n // TODO: Handle custom foreign keys if Better Auth passes them or we infer them\n const joinWhere: Where[] = [{ field: 'userId', value: result.id }];\n \n const limit = typeof joinConfig === 'object' ? joinConfig.limit : undefined;\n \n const joinResults = await runQuery(joinModel, joinWhere, undefined, limit);\n \n // Attach to result using pluralized name (simple heuristic)\n const pluralName = joinModel.endsWith('s') ? joinModel : joinModel + 's';\n (result as any)[pluralName] = joinResults;\n }\n }\n\n // console.log(`[Adapter] findOne final result:`, result);\n \n // Ensure Dates are Date objects if they are strings (basic fix for JSON/serialization issues)\n const fixDates = (obj: any) => {\n if (!obj) return obj;\n for (const key in obj) {\n if (typeof obj[key] === 'string' && /^\\d{4}-\\d{2}-\\d{2}T/.test(obj[key])) {\n obj[key] = new Date(obj[key]);\n } else if (typeof obj[key] === 'object' && obj[key] !== null) {\n if (Array.isArray(obj[key])) {\n obj[key].forEach((item: any) => fixDates(item));\n }\n }\n }\n return obj;\n };\n fixDates(result);\n\n if (select) {\n const selected: any = {};\n select.forEach(field => selected[field] = result[field]);\n // Ensure joined props are kept if they are not in select? \n // Usually select applies to the main model fields. \n // If join is requested, it implies we want those too.\n if (join) {\n for (const joinModel of Object.keys(join)) {\n const propName = joinModel.endsWith('s') ? joinModel : joinModel + 's';\n if ((result as any)[propName]) {\n selected[propName] = (result as any)[propName];\n }\n }\n }\n return selected;\n }\n return result;\n }\n return null;\n },\n\n async findMany({ model, where, limit, offset, sortBy }) {\n const results = await runQuery<any>(model, where, sortBy ? {[sortBy.field]: sortBy.direction} : undefined, limit, offset);\n return results;\n },\n\n async update({ model, where, update }) {\n // We need to find the records first to update them\n const results = await runQuery<any>(model, where);\n if (results.length === 0) return null;\n\n const mapName = getMapName(model);\n const map = client.getMap<string, any>(mapName);\n \n // Update implies modifying existing. \n // If multiple matches, update only first? The interface says \"Update may not return the updated data if multiple where clauses are provided\".\n // Usually update finds one.\n // But if where is implicit AND, it finds specific set.\n // Standard behavior for 'update' (singular) is update ONE.\n \n const item = results[0];\n const updatedItem = { ...item, ...update };\n map.set(item.id, updatedItem);\n \n return updatedItem;\n },\n\n async updateMany({ model, where, update }) {\n const results = await runQuery<any>(model, where);\n const mapName = getMapName(model);\n const map = client.getMap<string, any>(mapName);\n \n for (const item of results) {\n map.set(item.id, { ...item, ...update });\n }\n return results.length;\n },\n\n async delete({ model, where }) {\n const results = await runQuery<any>(model, where);\n const mapName = getMapName(model);\n const map = client.getMap<string, any>(mapName);\n \n if (results.length > 0) {\n map.remove(results[0].id);\n }\n },\n\n async deleteMany({ model, where }) {\n const results = await runQuery<any>(model, where);\n const mapName = getMapName(model);\n const map = client.getMap<string, any>(mapName);\n \n for (const item of results) {\n map.remove(item.id);\n }\n return results.length;\n },\n \n async count({ model, where }) {\n const results = await runQuery<any>(model, where);\n return results.length;\n },\n\n async transaction(callback) {\n // TopGun doesn't support atomic multi-map transactions yet.\n // We execute sequentially as per BetterAuth fallback.\n // But DBTransactionAdapter is Omit<DBAdapter, \"transaction\">.\n // We just pass 'this' as the transaction adapter (cast it).\n return callback(this as any); \n }\n };\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AA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AO,OAAoB,OAAO;AAE9C,YAAI,QAAQ,SAAS,GAAG;AACrB,cAAI,OAAO,QAAQ,CAAC,EAAE,EAAE;AAAA,QAC3B;AAAA,MACH;AAAA,MAEA,MAAM,WAAW,EAAE,OAAO,MAAM,GAAG;AAChC,cAAM,UAAU,MAAM,SAAc,OAAO,KAAK;AAChD,cAAM,UAAU,WAAW,KAAK;AAChC,cAAM,MAAM,OAAO,OAAoB,OAAO;AAE9C,mBAAW,QAAQ,SAAS;AACzB,cAAI,OAAO,KAAK,EAAE;AAAA,QACrB;AACA,eAAO,QAAQ;AAAA,MAClB;AAAA,MAEA,MAAM,MAAM,EAAE,OAAO,MAAM,GAAG;AAC3B,cAAM,UAAU,MAAM,SAAc,OAAO,KAAK;AAChD,eAAO,QAAQ;AAAA,MAClB;AAAA,MAEA,MAAM,YAAY,UAAU;AAKzB,eAAO,SAAS,IAAW;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
package/dist/index.mjs ADDED
@@ -0,0 +1,180 @@
1
+ // src/TopGunAdapter.ts
2
+ import { Predicates } from "@topgunbuild/client";
3
+ var topGunAdapter = (adapterOptions) => {
4
+ return (options) => {
5
+ const { client, modelMap = {} } = adapterOptions;
6
+ const getMapName = (model) => {
7
+ return modelMap[model] || `auth_${model}`;
8
+ };
9
+ const whereToPredicate = (where) => {
10
+ if (!where || where.length === 0) return void 0;
11
+ const predicates = where.map((w) => {
12
+ const field = w.field;
13
+ const value = w.value;
14
+ switch (w.operator) {
15
+ case "eq":
16
+ return Predicates.equal(field, value);
17
+ case "ne":
18
+ return Predicates.notEqual(field, value);
19
+ case "lt":
20
+ return Predicates.lessThan(field, value);
21
+ case "lte":
22
+ return Predicates.lessThanOrEqual(field, value);
23
+ case "gt":
24
+ return Predicates.greaterThan(field, value);
25
+ case "gte":
26
+ return Predicates.greaterThanOrEqual(field, value);
27
+ case "contains":
28
+ return Predicates.like(field, `%${value}%`);
29
+ case "starts_with":
30
+ return Predicates.like(field, `${value}%`);
31
+ case "ends_with":
32
+ return Predicates.like(field, `%${value}`);
33
+ case "in":
34
+ if (Array.isArray(value)) {
35
+ return Predicates.or(...value.map((v) => Predicates.equal(field, v)));
36
+ }
37
+ return Predicates.equal(field, value);
38
+ case "not_in":
39
+ if (Array.isArray(value)) {
40
+ return Predicates.and(...value.map((v) => Predicates.notEqual(field, v)));
41
+ }
42
+ return Predicates.notEqual(field, value);
43
+ default:
44
+ return Predicates.equal(field, value);
45
+ }
46
+ });
47
+ if (predicates.length === 1) return predicates[0];
48
+ return Predicates.and(...predicates);
49
+ };
50
+ const runQuery = async (model, where, sort, limit, offset) => {
51
+ const mapName = getMapName(model);
52
+ const predicate = where ? whereToPredicate(where) : void 0;
53
+ const filter = {
54
+ predicate,
55
+ sort,
56
+ limit,
57
+ offset
58
+ };
59
+ return new Promise((resolve) => {
60
+ const handle = client.query(mapName, filter);
61
+ const unsubscribe = handle.subscribe((results) => {
62
+ unsubscribe();
63
+ resolve(results);
64
+ });
65
+ });
66
+ };
67
+ return {
68
+ id: "topgun-adapter",
69
+ async create({ model, data }) {
70
+ const mapName = getMapName(model);
71
+ const id = data.id || crypto.randomUUID();
72
+ const record = { ...data, id };
73
+ const map = client.getMap(mapName);
74
+ map.set(id, record);
75
+ return record;
76
+ },
77
+ async findOne({ model, where, select, join }) {
78
+ const idCheck = where.find((w) => w.field === "id" && (w.operator === "eq" || w.operator === void 0));
79
+ if (idCheck && where.length === 1) {
80
+ const mapName = getMapName(model);
81
+ const map = client.getMap(mapName);
82
+ }
83
+ const results = await runQuery(model, where, void 0, 1);
84
+ if (results.length > 0) {
85
+ const result = results[0];
86
+ if (join) {
87
+ for (const [joinModel, joinConfig] of Object.entries(join)) {
88
+ if (joinConfig === false) continue;
89
+ const joinWhere = [{ field: "userId", value: result.id }];
90
+ const limit = typeof joinConfig === "object" ? joinConfig.limit : void 0;
91
+ const joinResults = await runQuery(joinModel, joinWhere, void 0, limit);
92
+ const pluralName = joinModel.endsWith("s") ? joinModel : joinModel + "s";
93
+ result[pluralName] = joinResults;
94
+ }
95
+ }
96
+ const fixDates = (obj) => {
97
+ if (!obj) return obj;
98
+ for (const key in obj) {
99
+ if (typeof obj[key] === "string" && /^\d{4}-\d{2}-\d{2}T/.test(obj[key])) {
100
+ obj[key] = new Date(obj[key]);
101
+ } else if (typeof obj[key] === "object" && obj[key] !== null) {
102
+ if (Array.isArray(obj[key])) {
103
+ obj[key].forEach((item) => fixDates(item));
104
+ }
105
+ }
106
+ }
107
+ return obj;
108
+ };
109
+ fixDates(result);
110
+ if (select) {
111
+ const selected = {};
112
+ select.forEach((field) => selected[field] = result[field]);
113
+ if (join) {
114
+ for (const joinModel of Object.keys(join)) {
115
+ const propName = joinModel.endsWith("s") ? joinModel : joinModel + "s";
116
+ if (result[propName]) {
117
+ selected[propName] = result[propName];
118
+ }
119
+ }
120
+ }
121
+ return selected;
122
+ }
123
+ return result;
124
+ }
125
+ return null;
126
+ },
127
+ async findMany({ model, where, limit, offset, sortBy }) {
128
+ const results = await runQuery(model, where, sortBy ? { [sortBy.field]: sortBy.direction } : void 0, limit, offset);
129
+ return results;
130
+ },
131
+ async update({ model, where, update }) {
132
+ const results = await runQuery(model, where);
133
+ if (results.length === 0) return null;
134
+ const mapName = getMapName(model);
135
+ const map = client.getMap(mapName);
136
+ const item = results[0];
137
+ const updatedItem = { ...item, ...update };
138
+ map.set(item.id, updatedItem);
139
+ return updatedItem;
140
+ },
141
+ async updateMany({ model, where, update }) {
142
+ const results = await runQuery(model, where);
143
+ const mapName = getMapName(model);
144
+ const map = client.getMap(mapName);
145
+ for (const item of results) {
146
+ map.set(item.id, { ...item, ...update });
147
+ }
148
+ return results.length;
149
+ },
150
+ async delete({ model, where }) {
151
+ const results = await runQuery(model, where);
152
+ const mapName = getMapName(model);
153
+ const map = client.getMap(mapName);
154
+ if (results.length > 0) {
155
+ map.remove(results[0].id);
156
+ }
157
+ },
158
+ async deleteMany({ model, where }) {
159
+ const results = await runQuery(model, where);
160
+ const mapName = getMapName(model);
161
+ const map = client.getMap(mapName);
162
+ for (const item of results) {
163
+ map.remove(item.id);
164
+ }
165
+ return results.length;
166
+ },
167
+ async count({ model, where }) {
168
+ const results = await runQuery(model, where);
169
+ return results.length;
170
+ },
171
+ async transaction(callback) {
172
+ return callback(this);
173
+ }
174
+ };
175
+ };
176
+ };
177
+ export {
178
+ topGunAdapter
179
+ };
180
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/TopGunAdapter.ts"],"sourcesContent":["import { TopGunClient, Predicates } from '@topgunbuild/client';\nimport type { BetterAuthOptions } from 'better-auth';\nimport type { \n DBAdapter, \n Where,\n DBAdapterInstance\n} from 'better-auth/adapters';\nimport type { PredicateNode } from '@topgunbuild/core';\n\nexport interface TopGunAdapterOptions {\n client: TopGunClient;\n /**\n * Map model names to TopGun map names.\n * Default: \"auth_user\", \"auth_session\", etc.\n */\n modelMap?: Record<string, string>;\n}\n\nexport const topGunAdapter = (adapterOptions: TopGunAdapterOptions): DBAdapterInstance => {\n return (options: BetterAuthOptions): DBAdapter => {\n const { client, modelMap = {} } = adapterOptions;\n\n const getMapName = (model: string) => {\n return modelMap[model] || `auth_${model}`;\n };\n\n const whereToPredicate = (where: Where[]): PredicateNode | undefined => {\n if (!where || where.length === 0) return undefined;\n\n const predicates: PredicateNode[] = where.map(w => {\n const field = w.field;\n const value = w.value;\n \n switch (w.operator) {\n case 'eq': return Predicates.equal(field, value);\n case 'ne': return Predicates.notEqual(field, value);\n case 'lt': return Predicates.lessThan(field, value);\n case 'lte': return Predicates.lessThanOrEqual(field, value);\n case 'gt': return Predicates.greaterThan(field, value);\n case 'gte': return Predicates.greaterThanOrEqual(field, value);\n case 'contains': return Predicates.like(field, `%${value}%`);\n case 'starts_with': return Predicates.like(field, `${value}%`);\n case 'ends_with': return Predicates.like(field, `%${value}`);\n case 'in': \n if (Array.isArray(value)) {\n return Predicates.or(...value.map(v => Predicates.equal(field, v)));\n }\n return Predicates.equal(field, value);\n case 'not_in':\n if (Array.isArray(value)) {\n return Predicates.and(...value.map(v => Predicates.notEqual(field, v)));\n }\n return Predicates.notEqual(field, value);\n default: return Predicates.equal(field, value);\n }\n });\n\n // BetterAuth Where[] implies AND\n if (predicates.length === 1) return predicates[0];\n return Predicates.and(...predicates);\n };\n\n const runQuery = async <T>(model: string, where?: Where[], sort?: any, limit?: number, offset?: number): Promise<T[]> => {\n const mapName = getMapName(model);\n const predicate = where ? whereToPredicate(where) : undefined;\n \n const filter = {\n predicate,\n sort,\n limit,\n offset\n };\n\n // We use client.query which subscribes. We wait for the first result.\n // TopGun QueryHandle is reactive. We need a one-shot fetch.\n \n return new Promise((resolve) => {\n const handle = client.query<T>(mapName, filter);\n \n // Subscribe returns an unsubscribe function\n const unsubscribe = handle.subscribe((results: T[]) => {\n unsubscribe();\n resolve(results);\n });\n });\n };\n\n return {\n id: 'topgun-adapter',\n \n async create({ model, data }) {\n const mapName = getMapName(model);\n const id = (data as any).id || crypto.randomUUID();\n const record = { ...data, id };\n \n // Use LWWMap for standard records\n const map = client.getMap<string, any>(mapName);\n map.set(id, record);\n \n // map.set is optimistic and writes to local storage/sync engine.\n // Ideally we wait for confirmation? TopGun doesn't expose Promise for set completion easily \n // (it returns the record). But SyncEngine queues it.\n \n return record as any;\n },\n\n async findOne({ model, where, select, join }) {\n // Optimization: If where is just ID check, use getMap().get()\n const idCheck = where.find(w => w.field === 'id' && (w.operator === 'eq' || w.operator === undefined));\n if (idCheck && where.length === 1) {\n const mapName = getMapName(model);\n const map = client.getMap<string, any>(mapName);\n // LWWMap.get is synchronous from memory (loaded from storage).\n // If we haven't loaded yet, we might miss it.\n // Ideally we should ensure map is loaded.\n // TopGunClient.getMap returns immediately but starts restoring in background.\n // This creates a race condition for cold start.\n \n // Workaround: Use runQuery which waits for initial load via QueryHandle -> loadInitialLocalData\n // But for simple ID, query is overkill?\n // Let's use runQuery to be safe and consistent.\n }\n\n const results = await runQuery<any>(model, where, undefined, 1);\n \n if (results.length > 0) {\n const result = results[0];\n\n // Handle Join\n if (join) {\n for (const [joinModel, joinConfig] of Object.entries(join)) {\n if (joinConfig === false) continue;\n \n // Assume standard relation on userId\n // TODO: Handle custom foreign keys if Better Auth passes them or we infer them\n const joinWhere: Where[] = [{ field: 'userId', value: result.id }];\n \n const limit = typeof joinConfig === 'object' ? joinConfig.limit : undefined;\n \n const joinResults = await runQuery(joinModel, joinWhere, undefined, limit);\n \n // Attach to result using pluralized name (simple heuristic)\n const pluralName = joinModel.endsWith('s') ? joinModel : joinModel + 's';\n (result as any)[pluralName] = joinResults;\n }\n }\n\n // console.log(`[Adapter] findOne final result:`, result);\n \n // Ensure Dates are Date objects if they are strings (basic fix for JSON/serialization issues)\n const fixDates = (obj: any) => {\n if (!obj) return obj;\n for (const key in obj) {\n if (typeof obj[key] === 'string' && /^\\d{4}-\\d{2}-\\d{2}T/.test(obj[key])) {\n obj[key] = new Date(obj[key]);\n } else if (typeof obj[key] === 'object' && obj[key] !== null) {\n if (Array.isArray(obj[key])) {\n obj[key].forEach((item: any) => fixDates(item));\n }\n }\n }\n return obj;\n };\n fixDates(result);\n\n if (select) {\n const selected: any = {};\n select.forEach(field => selected[field] = result[field]);\n // Ensure joined props are kept if they are not in select? \n // Usually select applies to the main model fields. \n // If join is requested, it implies we want those too.\n if (join) {\n for (const joinModel of Object.keys(join)) {\n const propName = joinModel.endsWith('s') ? joinModel : joinModel + 's';\n if ((result as any)[propName]) {\n selected[propName] = (result as any)[propName];\n }\n }\n }\n return selected;\n }\n return result;\n }\n return null;\n },\n\n async findMany({ model, where, limit, offset, sortBy }) {\n const results = await runQuery<any>(model, where, sortBy ? {[sortBy.field]: sortBy.direction} : undefined, limit, offset);\n return results;\n },\n\n async update({ model, where, update }) {\n // We need to find the records first to update them\n const results = await runQuery<any>(model, where);\n if (results.length === 0) return null;\n\n const mapName = getMapName(model);\n const map = client.getMap<string, any>(mapName);\n \n // Update implies modifying existing. \n // If multiple matches, update only first? The interface says \"Update may not return the updated data if multiple where clauses are provided\".\n // Usually update finds one.\n // But if where is implicit AND, it finds specific set.\n // Standard behavior for 'update' (singular) is update ONE.\n \n const item = results[0];\n const updatedItem = { ...item, ...update };\n map.set(item.id, updatedItem);\n \n return updatedItem;\n },\n\n async updateMany({ model, where, update }) {\n const results = await runQuery<any>(model, where);\n const mapName = getMapName(model);\n const map = client.getMap<string, any>(mapName);\n \n for (const item of results) {\n map.set(item.id, { ...item, ...update });\n }\n return results.length;\n },\n\n async delete({ model, where }) {\n const results = await runQuery<any>(model, where);\n const mapName = getMapName(model);\n const map = client.getMap<string, any>(mapName);\n \n if (results.length > 0) {\n map.remove(results[0].id);\n }\n },\n\n async deleteMany({ model, where }) {\n const results = await runQuery<any>(model, where);\n const mapName = getMapName(model);\n const map = client.getMap<string, any>(mapName);\n \n for (const item of results) {\n map.remove(item.id);\n }\n return results.length;\n },\n \n async count({ model, where }) {\n const results = await runQuery<any>(model, where);\n return results.length;\n },\n\n async transaction(callback) {\n // TopGun doesn't support atomic multi-map transactions yet.\n // We execute sequentially as per BetterAuth fallback.\n // But DBTransactionAdapter is Omit<DBAdapter, \"transaction\">.\n // We just pass 'this' as the transaction adapter (cast it).\n return callback(this as any); \n }\n };\n };\n};\n"],"mappings":";AAAA,SAAuB,kBAAkB;AAkBlC,IAAM,gBAAgB,CAAC,mBAA4D;AACxF,SAAO,CAAC,YAA0C;AAChD,UAAM,EAAE,QAAQ,WAAW,CAAC,EAAE,IAAI;AAElC,UAAM,aAAa,CAAC,UAAkB;AACpC,aAAO,SAAS,KAAK,KAAK,QAAQ,KAAK;AAAA,IACzC;AAEA,UAAM,mBAAmB,CAAC,UAA8C;AACtE,UAAI,CAAC,SAAS,MAAM,WAAW,EAAG,QAAO;AAEzC,YAAM,aAA8B,MAAM,IAAI,OAAK;AACjD,cAAM,QAAQ,EAAE;AAChB,cAAM,QAAQ,EAAE;AAEhB,gBAAQ,EAAE,UAAU;AAAA,UAClB,KAAK;AAAM,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AQ;AAAA,MAClB;AAAA,MAEA,MAAM,YAAY,UAAU;AAKzB,eAAO,SAAS,IAAW;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@topgunbuild/adapter-better-auth",
3
+ "version": "0.1.0",
4
+ "main": "./dist/index.js",
5
+ "module": "./dist/index.mjs",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.mjs",
11
+ "require": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "sideEffects": false,
18
+ "publishConfig": {
19
+ "access": "public"
20
+ },
21
+ "dependencies": {
22
+ "better-auth": "^1.0.0",
23
+ "@topgunbuild/client": "0.1.0",
24
+ "@topgunbuild/core": "0.1.0"
25
+ },
26
+ "devDependencies": {
27
+ "@types/jest": "^29.5.14",
28
+ "jest": "^29.7.0",
29
+ "ts-jest": "^29.1.1",
30
+ "typescript": "^5.0.0"
31
+ },
32
+ "engines": {
33
+ "node": ">=18"
34
+ },
35
+ "license": "BSL-1.1",
36
+ "scripts": {
37
+ "build": "tsup",
38
+ "test": "jest",
39
+ "test:coverage": "jest --coverage"
40
+ }
41
+ }