@proofkit/better-auth 0.2.4 → 0.3.1-beta.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/dist/esm/adapter.d.ts +3 -3
- package/dist/esm/adapter.js +141 -76
- package/dist/esm/adapter.js.map +1 -1
- package/dist/esm/better-auth-cli/utils/add-svelte-kit-env-modules.js +4 -12
- package/dist/esm/better-auth-cli/utils/add-svelte-kit-env-modules.js.map +1 -1
- package/dist/esm/better-auth-cli/utils/get-config.js +12 -21
- package/dist/esm/better-auth-cli/utils/get-config.js.map +1 -1
- package/dist/esm/better-auth-cli/utils/get-tsconfig-info.js +4 -11
- package/dist/esm/better-auth-cli/utils/get-tsconfig-info.js.map +1 -1
- package/dist/esm/cli/index.js +14 -26
- package/dist/esm/cli/index.js.map +1 -1
- package/dist/esm/migrate.d.ts +6 -6
- package/dist/esm/migrate.js +72 -44
- package/dist/esm/migrate.js.map +1 -1
- package/dist/esm/odata/index.d.ts +17 -91
- package/dist/esm/odata/index.js +141 -67
- package/dist/esm/odata/index.js.map +1 -1
- package/package.json +9 -7
- package/src/adapter.ts +171 -93
- package/src/better-auth-cli/utils/add-svelte-kit-env-modules.ts +68 -80
- package/src/better-auth-cli/utils/get-config.ts +16 -30
- package/src/better-auth-cli/utils/get-tsconfig-info.ts +12 -20
- package/src/cli/index.ts +13 -31
- package/src/index.ts +1 -0
- package/src/migrate.ts +87 -74
- package/src/odata/index.ts +195 -78
package/dist/esm/adapter.d.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AdapterDebugLogs, CleanedWhere } from 'better-auth/adapters';
|
|
2
2
|
import { FmOdataConfig } from './odata.js';
|
|
3
3
|
interface FileMakerAdapterConfig {
|
|
4
4
|
debugLogs?: AdapterDebugLogs;
|
|
5
5
|
usePlural?: boolean;
|
|
6
6
|
odata: FmOdataConfig;
|
|
7
7
|
}
|
|
8
|
-
export
|
|
8
|
+
export interface AdapterOptions {
|
|
9
9
|
config: FileMakerAdapterConfig;
|
|
10
|
-
}
|
|
10
|
+
}
|
|
11
11
|
export declare function parseWhere(where?: CleanedWhere[]): string;
|
|
12
12
|
export declare const FileMakerAdapter: (_config?: FileMakerAdapterConfig) => (options: import('better-auth').BetterAuthOptions) => import('better-auth').Adapter;
|
|
13
13
|
export {};
|
package/dist/esm/adapter.js
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
|
+
import { logger } from "better-auth";
|
|
1
2
|
import { createAdapter } from "better-auth/adapters";
|
|
2
|
-
import
|
|
3
|
+
import buildQuery from "odata-query";
|
|
3
4
|
import { z, prettifyError } from "zod/v4";
|
|
4
|
-
import {
|
|
5
|
+
import { createRawFetch } from "./odata/index.js";
|
|
5
6
|
const configSchema = z.object({
|
|
6
7
|
debugLogs: z.unknown().optional(),
|
|
7
8
|
usePlural: z.boolean().optional(),
|
|
8
9
|
odata: z.object({
|
|
9
10
|
serverUrl: z.url(),
|
|
10
|
-
auth: z.union([
|
|
11
|
-
z.object({ username: z.string(), password: z.string() }),
|
|
12
|
-
z.object({ apiKey: z.string() })
|
|
13
|
-
]),
|
|
11
|
+
auth: z.union([z.object({ username: z.string(), password: z.string() }), z.object({ apiKey: z.string() })]),
|
|
14
12
|
database: z.string().endsWith(".fmp12")
|
|
15
13
|
})
|
|
16
14
|
});
|
|
@@ -23,21 +21,36 @@ const defaultConfig = {
|
|
|
23
21
|
database: ""
|
|
24
22
|
}
|
|
25
23
|
};
|
|
24
|
+
const FIELD_SPECIAL_CHARS_REGEX = /[\s_]/;
|
|
25
|
+
const ISO_DATE_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z?$/;
|
|
26
26
|
function parseWhere(where) {
|
|
27
|
-
if (!where || where.length === 0)
|
|
27
|
+
if (!where || where.length === 0) {
|
|
28
|
+
return "";
|
|
29
|
+
}
|
|
28
30
|
function quoteField(field, value) {
|
|
29
|
-
if (value === null || value instanceof Date)
|
|
30
|
-
|
|
31
|
+
if (value === null || value instanceof Date) {
|
|
32
|
+
return field;
|
|
33
|
+
}
|
|
34
|
+
if (field === "id" || FIELD_SPECIAL_CHARS_REGEX.test(field)) {
|
|
35
|
+
return `"${field}"`;
|
|
36
|
+
}
|
|
31
37
|
return field;
|
|
32
38
|
}
|
|
33
39
|
function formatValue(value) {
|
|
34
|
-
if (value === null)
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
if (
|
|
40
|
+
if (value === null) {
|
|
41
|
+
return "null";
|
|
42
|
+
}
|
|
43
|
+
if (typeof value === "boolean") {
|
|
44
|
+
return value ? "true" : "false";
|
|
45
|
+
}
|
|
46
|
+
if (value instanceof Date) {
|
|
47
|
+
return value.toISOString();
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(value)) {
|
|
50
|
+
return `(${value.map(formatValue).join(",")})`;
|
|
51
|
+
}
|
|
38
52
|
if (typeof value === "string") {
|
|
39
|
-
|
|
40
|
-
if (isoDateRegex.test(value)) {
|
|
53
|
+
if (ISO_DATE_REGEX.test(value)) {
|
|
41
54
|
return value;
|
|
42
55
|
}
|
|
43
56
|
return `'${value.replace(/'/g, "''")}'`;
|
|
@@ -55,7 +68,9 @@ function parseWhere(where) {
|
|
|
55
68
|
const clauses = [];
|
|
56
69
|
for (let i = 0; i < where.length; i++) {
|
|
57
70
|
const cond = where[i];
|
|
58
|
-
if (!cond)
|
|
71
|
+
if (!cond) {
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
59
74
|
const field = quoteField(cond.field, cond.value);
|
|
60
75
|
let clause = "";
|
|
61
76
|
switch (cond.operator) {
|
|
@@ -98,7 +113,7 @@ const FileMakerAdapter = (_config = defaultConfig) => {
|
|
|
98
113
|
throw new Error(`Invalid configuration: ${prettifyError(parsed.error)}`);
|
|
99
114
|
}
|
|
100
115
|
const config = parsed.data;
|
|
101
|
-
const fetch =
|
|
116
|
+
const { fetch } = createRawFetch({
|
|
102
117
|
...config.odata,
|
|
103
118
|
logging: config.debugLogs ? "verbose" : "none"
|
|
104
119
|
});
|
|
@@ -119,10 +134,9 @@ const FileMakerAdapter = (_config = defaultConfig) => {
|
|
|
119
134
|
supportsNumericIds: false
|
|
120
135
|
// Whether the database supports auto-incrementing numeric IDs. (Default: true)
|
|
121
136
|
},
|
|
122
|
-
adapter: (
|
|
137
|
+
adapter: () => {
|
|
123
138
|
return {
|
|
124
|
-
|
|
125
|
-
create: async ({ data, model, select }) => {
|
|
139
|
+
create: async ({ data, model }) => {
|
|
126
140
|
if (model === "session") {
|
|
127
141
|
console.log("session", data);
|
|
128
142
|
}
|
|
@@ -140,11 +154,11 @@ const FileMakerAdapter = (_config = defaultConfig) => {
|
|
|
140
154
|
var _a;
|
|
141
155
|
const filter = parseWhere(where);
|
|
142
156
|
logger.debug("$filter", filter);
|
|
143
|
-
const
|
|
157
|
+
const query = buildQuery({
|
|
158
|
+
filter: filter.length > 0 ? filter : void 0
|
|
159
|
+
});
|
|
160
|
+
const result = await fetch(`/${model}/$count${query}`, {
|
|
144
161
|
method: "GET",
|
|
145
|
-
query: {
|
|
146
|
-
$filter: filter
|
|
147
|
-
},
|
|
148
162
|
output: z.object({ value: z.number() })
|
|
149
163
|
});
|
|
150
164
|
if (!result.data) {
|
|
@@ -156,12 +170,12 @@ const FileMakerAdapter = (_config = defaultConfig) => {
|
|
|
156
170
|
var _a, _b;
|
|
157
171
|
const filter = parseWhere(where);
|
|
158
172
|
logger.debug("$filter", filter);
|
|
159
|
-
const
|
|
173
|
+
const query = buildQuery({
|
|
174
|
+
top: 1,
|
|
175
|
+
filter: filter.length > 0 ? filter : void 0
|
|
176
|
+
});
|
|
177
|
+
const result = await fetch(`/${model}${query}`, {
|
|
160
178
|
method: "GET",
|
|
161
|
-
query: {
|
|
162
|
-
...filter.length > 0 ? { $filter: filter } : {},
|
|
163
|
-
$top: 1
|
|
164
|
-
},
|
|
165
179
|
output: z.object({ value: z.array(z.any()) })
|
|
166
180
|
});
|
|
167
181
|
if (result.error) {
|
|
@@ -172,79 +186,130 @@ const FileMakerAdapter = (_config = defaultConfig) => {
|
|
|
172
186
|
findMany: async ({ model, where, limit, offset, sortBy }) => {
|
|
173
187
|
var _a;
|
|
174
188
|
const filter = parseWhere(where);
|
|
175
|
-
logger.debug("
|
|
176
|
-
const
|
|
189
|
+
logger.debug("FIND MANY", { where, filter });
|
|
190
|
+
const query = buildQuery({
|
|
191
|
+
top: limit,
|
|
192
|
+
skip: offset,
|
|
193
|
+
orderBy: sortBy ? `${sortBy.field} ${sortBy.direction ?? "asc"}` : void 0,
|
|
194
|
+
filter: filter.length > 0 ? filter : void 0
|
|
195
|
+
});
|
|
196
|
+
logger.debug("QUERY", query);
|
|
197
|
+
const result = await fetch(`/${model}${query}`, {
|
|
177
198
|
method: "GET",
|
|
178
|
-
query: {
|
|
179
|
-
...filter.length > 0 ? { $filter: filter } : {},
|
|
180
|
-
$top: limit,
|
|
181
|
-
$skip: offset,
|
|
182
|
-
...sortBy ? { $orderby: `"${sortBy.field}" ${sortBy.direction ?? "asc"}` } : {}
|
|
183
|
-
},
|
|
184
199
|
output: z.object({ value: z.array(z.any()) })
|
|
185
200
|
});
|
|
186
|
-
|
|
201
|
+
logger.debug("RESULT", result);
|
|
202
|
+
if (result.error) {
|
|
187
203
|
throw new Error("Failed to find records");
|
|
188
204
|
}
|
|
189
|
-
return ((_a =
|
|
205
|
+
return ((_a = result.data) == null ? void 0 : _a.value) ?? [];
|
|
190
206
|
},
|
|
191
207
|
delete: async ({ model, where }) => {
|
|
208
|
+
var _a, _b, _c;
|
|
192
209
|
const filter = parseWhere(where);
|
|
210
|
+
console.log("DELETE", { model, where, filter });
|
|
193
211
|
logger.debug("$filter", filter);
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
212
|
+
const query = buildQuery({
|
|
213
|
+
top: 1,
|
|
214
|
+
select: [`"id"`],
|
|
215
|
+
filter: filter.length > 0 ? filter : void 0
|
|
216
|
+
});
|
|
217
|
+
const toDelete = await fetch(`/${model}${query}`, {
|
|
218
|
+
method: "GET",
|
|
219
|
+
output: z.object({ value: z.array(z.object({ id: z.string() })) })
|
|
220
|
+
});
|
|
221
|
+
const id = (_c = (_b = (_a = toDelete.data) == null ? void 0 : _a.value) == null ? void 0 : _b[0]) == null ? void 0 : _c.id;
|
|
222
|
+
if (!id) {
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const result = await fetch(`/${model}('${id}')`, {
|
|
226
|
+
method: "DELETE"
|
|
201
227
|
});
|
|
202
228
|
if (result.error) {
|
|
229
|
+
console.log("DELETE ERROR", result.error);
|
|
203
230
|
throw new Error("Failed to delete record");
|
|
204
231
|
}
|
|
205
232
|
},
|
|
206
233
|
deleteMany: async ({ model, where }) => {
|
|
234
|
+
var _a, _b;
|
|
207
235
|
const filter = parseWhere(where);
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
const result = await fetch(`/${model}/$count`, {
|
|
213
|
-
method: "DELETE",
|
|
214
|
-
query: {
|
|
215
|
-
...where.length > 0 ? { $filter: filter } : {}
|
|
216
|
-
},
|
|
217
|
-
output: z.coerce.number()
|
|
236
|
+
console.log("DELETE MANY", { model, where, filter });
|
|
237
|
+
const query = buildQuery({
|
|
238
|
+
select: [`"id"`],
|
|
239
|
+
filter: filter.length > 0 ? filter : void 0
|
|
218
240
|
});
|
|
219
|
-
|
|
220
|
-
|
|
241
|
+
const rows = await fetch(`/${model}${query}`, {
|
|
242
|
+
method: "GET",
|
|
243
|
+
output: z.object({ value: z.array(z.object({ id: z.string() })) })
|
|
244
|
+
});
|
|
245
|
+
const ids = ((_b = (_a = rows.data) == null ? void 0 : _a.value) == null ? void 0 : _b.map((r) => r.id)) ?? [];
|
|
246
|
+
let deleted = 0;
|
|
247
|
+
for (const id of ids) {
|
|
248
|
+
const res = await fetch(`/${model}('${id}')`, {
|
|
249
|
+
method: "DELETE"
|
|
250
|
+
});
|
|
251
|
+
if (!res.error) {
|
|
252
|
+
deleted++;
|
|
253
|
+
}
|
|
221
254
|
}
|
|
222
|
-
return
|
|
255
|
+
return deleted;
|
|
223
256
|
},
|
|
224
257
|
update: async ({ model, where, update }) => {
|
|
225
|
-
var _a, _b;
|
|
226
|
-
const
|
|
258
|
+
var _a, _b, _c;
|
|
259
|
+
const filter = parseWhere(where);
|
|
260
|
+
logger.debug("UPDATE", { model, where, update });
|
|
261
|
+
logger.debug("$filter", filter);
|
|
262
|
+
const query = buildQuery({
|
|
263
|
+
select: [`"id"`],
|
|
264
|
+
filter: filter.length > 0 ? filter : void 0
|
|
265
|
+
});
|
|
266
|
+
const existing = await fetch(`/${model}${query}`, {
|
|
267
|
+
method: "GET",
|
|
268
|
+
output: z.object({ value: z.array(z.object({ id: z.string() })) })
|
|
269
|
+
});
|
|
270
|
+
logger.debug("EXISTING", existing.data);
|
|
271
|
+
const id = (_c = (_b = (_a = existing.data) == null ? void 0 : _a.value) == null ? void 0 : _b[0]) == null ? void 0 : _c.id;
|
|
272
|
+
if (!id) {
|
|
273
|
+
return null;
|
|
274
|
+
}
|
|
275
|
+
const patchRes = await fetch(`/${model}('${id}')`, {
|
|
227
276
|
method: "PATCH",
|
|
228
|
-
|
|
229
|
-
...where.length > 0 ? { $filter: parseWhere(where) } : {},
|
|
230
|
-
$top: 1,
|
|
231
|
-
$select: [`"id"`]
|
|
232
|
-
},
|
|
233
|
-
body: update,
|
|
234
|
-
output: z.object({ value: z.array(z.any()) })
|
|
277
|
+
body: update
|
|
235
278
|
});
|
|
236
|
-
|
|
279
|
+
logger.debug("PATCH RES", patchRes.data);
|
|
280
|
+
if (patchRes.error) {
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
const readBack = await fetch(`/${model}('${id}')`, {
|
|
284
|
+
method: "GET",
|
|
285
|
+
output: z.record(z.string(), z.unknown())
|
|
286
|
+
});
|
|
287
|
+
logger.debug("READ BACK", readBack.data);
|
|
288
|
+
return readBack.data ?? null;
|
|
237
289
|
},
|
|
238
290
|
updateMany: async ({ model, where, update }) => {
|
|
291
|
+
var _a, _b;
|
|
239
292
|
const filter = parseWhere(where);
|
|
240
|
-
const
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
...where.length > 0 ? { $filter: filter } : {}
|
|
244
|
-
},
|
|
245
|
-
body: update
|
|
293
|
+
const query = buildQuery({
|
|
294
|
+
select: [`"id"`],
|
|
295
|
+
filter: filter.length > 0 ? filter : void 0
|
|
246
296
|
});
|
|
247
|
-
|
|
297
|
+
const rows = await fetch(`/${model}${query}`, {
|
|
298
|
+
method: "GET",
|
|
299
|
+
output: z.object({ value: z.array(z.object({ id: z.string() })) })
|
|
300
|
+
});
|
|
301
|
+
const ids = ((_b = (_a = rows.data) == null ? void 0 : _a.value) == null ? void 0 : _b.map((r) => r.id)) ?? [];
|
|
302
|
+
let updated = 0;
|
|
303
|
+
for (const id of ids) {
|
|
304
|
+
const res = await fetch(`/${model}('${id}')`, {
|
|
305
|
+
method: "PATCH",
|
|
306
|
+
body: update
|
|
307
|
+
});
|
|
308
|
+
if (!res.error) {
|
|
309
|
+
updated++;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return updated;
|
|
248
313
|
}
|
|
249
314
|
};
|
|
250
315
|
}
|
package/dist/esm/adapter.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.js","sources":["../../src/adapter.ts"],"sourcesContent":["import {\n CleanedWhere,\n createAdapter,\n type AdapterDebugLogs,\n} from \"better-auth/adapters\";\nimport { createFmOdataFetch, type FmOdataConfig } from \"./odata\";\nimport { prettifyError, z } from \"zod/v4\";\nimport { logger } from \"better-auth\";\n\nconst configSchema = z.object({\n debugLogs: z.unknown().optional(),\n usePlural: z.boolean().optional(),\n odata: z.object({\n serverUrl: z.url(),\n auth: z.union([\n z.object({ username: z.string(), password: z.string() }),\n z.object({ apiKey: z.string() }),\n ]),\n database: z.string().endsWith(\".fmp12\"),\n }),\n});\n\ninterface FileMakerAdapterConfig {\n /**\n * Helps you debug issues with the adapter.\n */\n debugLogs?: AdapterDebugLogs;\n /**\n * If the table names in the schema are plural.\n */\n usePlural?: boolean;\n\n /**\n * Connection details for the FileMaker server.\n */\n odata: FmOdataConfig;\n}\n\nexport type AdapterOptions = {\n config: FileMakerAdapterConfig;\n};\n\nconst defaultConfig: Required<FileMakerAdapterConfig> = {\n debugLogs: false,\n usePlural: false,\n odata: {\n serverUrl: \"\",\n auth: { username: \"\", password: \"\" },\n database: \"\",\n },\n};\n\n/**\n * Parse the where clause to an OData filter string.\n * @param where - The where clause to parse.\n * @returns The OData filter string.\n * @internal\n */\nexport function parseWhere(where?: CleanedWhere[]): string {\n if (!where || where.length === 0) return \"\";\n\n // Helper to quote field names with special chars or if field is 'id'\n function quoteField(field: string, value?: any) {\n // Never quote for null or date values (per test expectations)\n if (value === null || value instanceof Date) return field;\n // Always quote if field is 'id' or has space or underscore\n if (field === \"id\" || /[\\s_]/.test(field)) return `\"${field}\"`;\n return field;\n }\n\n // Helper to format values for OData\n function formatValue(value: any): string {\n if (value === null) return \"null\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (value instanceof Date) return value.toISOString();\n if (Array.isArray(value)) return `(${value.map(formatValue).join(\",\")})`;\n\n // Handle strings - check if it's an ISO date string first\n if (typeof value === \"string\") {\n // Check if it's an ISO date string (YYYY-MM-DDTHH:mm:ss.sssZ format)\n const isoDateRegex = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?Z?$/;\n if (isoDateRegex.test(value)) {\n return value; // Return ISO date strings without quotes\n }\n return `'${value.replace(/'/g, \"''\")}'`; // Regular strings get quotes\n }\n\n return value?.toString() ?? \"\";\n }\n\n // Map our operators to OData\n const opMap: Record<string, string> = {\n eq: \"eq\",\n ne: \"ne\",\n lt: \"lt\",\n lte: \"le\",\n gt: \"gt\",\n gte: \"ge\",\n };\n\n // Build each clause\n const clauses: string[] = [];\n for (let i = 0; i < where.length; i++) {\n const cond = where[i];\n if (!cond) continue;\n const field = quoteField(cond.field, cond.value);\n let clause = \"\";\n switch (cond.operator) {\n case \"eq\":\n case \"ne\":\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\":\n clause = `${field} ${opMap[cond.operator!]} ${formatValue(cond.value)}`;\n break;\n case \"in\":\n if (Array.isArray(cond.value)) {\n clause = cond.value\n .map((v) => `${field} eq ${formatValue(v)}`)\n .join(\" or \");\n clause = `(${clause})`;\n }\n break;\n case \"contains\":\n clause = `contains(${field}, ${formatValue(cond.value)})`;\n break;\n case \"starts_with\":\n clause = `startswith(${field}, ${formatValue(cond.value)})`;\n break;\n case \"ends_with\":\n clause = `endswith(${field}, ${formatValue(cond.value)})`;\n break;\n default:\n clause = `${field} eq ${formatValue(cond.value)}`;\n }\n clauses.push(clause);\n // Add connector if not last\n if (i < where.length - 1) {\n clauses.push((cond.connector || \"and\").toLowerCase());\n }\n }\n return clauses.join(\" \");\n}\n\nexport const FileMakerAdapter = (\n _config: FileMakerAdapterConfig = defaultConfig,\n) => {\n const parsed = configSchema.loose().safeParse(_config);\n\n if (!parsed.success) {\n throw new Error(`Invalid configuration: ${prettifyError(parsed.error)}`);\n }\n const config = parsed.data;\n\n const fetch = createFmOdataFetch({\n ...config.odata,\n logging: config.debugLogs ? \"verbose\" : \"none\",\n });\n\n return createAdapter({\n config: {\n adapterId: \"filemaker\",\n adapterName: \"FileMaker\",\n usePlural: config.usePlural ?? false, // Whether the table names in the schema are plural.\n debugLogs: config.debugLogs ?? false, // Whether to enable debug logs.\n supportsJSON: false, // Whether the database supports JSON. (Default: false)\n supportsDates: false, // Whether the database supports dates. (Default: true)\n supportsBooleans: false, // Whether the database supports booleans. (Default: true)\n supportsNumericIds: false, // Whether the database supports auto-incrementing numeric IDs. (Default: true)\n },\n adapter: ({ options }) => {\n return {\n options: { config },\n create: async ({ data, model, select }) => {\n if (model === \"session\") {\n console.log(\"session\", data);\n }\n\n const result = await fetch(`/${model}`, {\n method: \"POST\",\n body: data,\n output: z.looseObject({ id: z.string() }),\n });\n\n if (result.error) {\n throw new Error(\"Failed to create record\");\n }\n\n return result.data as any;\n },\n count: async ({ model, where }) => {\n const filter = parseWhere(where);\n logger.debug(\"$filter\", filter);\n const result = await fetch(`/${model}/$count`, {\n method: \"GET\",\n query: {\n $filter: filter,\n },\n output: z.object({ value: z.number() }),\n });\n if (!result.data) {\n throw new Error(\"Failed to count records\");\n }\n return result.data?.value ?? 0;\n },\n findOne: async ({ model, where }) => {\n const filter = parseWhere(where);\n logger.debug(\"$filter\", filter);\n const result = await fetch(`/${model}`, {\n method: \"GET\",\n query: {\n ...(filter.length > 0 ? { $filter: filter } : {}),\n $top: 1,\n },\n output: z.object({ value: z.array(z.any()) }),\n });\n if (result.error) {\n throw new Error(\"Failed to find record\");\n }\n return result.data?.value?.[0] ?? null;\n },\n findMany: async ({ model, where, limit, offset, sortBy }) => {\n const filter = parseWhere(where);\n logger.debug(\"$filter\", filter);\n\n const rows = await fetch(`/${model}`, {\n method: \"GET\",\n query: {\n ...(filter.length > 0 ? { $filter: filter } : {}),\n $top: limit,\n $skip: offset,\n ...(sortBy\n ? { $orderby: `\"${sortBy.field}\" ${sortBy.direction ?? \"asc\"}` }\n : {}),\n },\n output: z.object({ value: z.array(z.any()) }),\n });\n if (rows.error) {\n throw new Error(\"Failed to find records\");\n }\n return rows.data?.value ?? [];\n },\n delete: async ({ model, where }) => {\n const filter = parseWhere(where);\n logger.debug(\"$filter\", filter);\n console.log(\"delete\", model, where, filter);\n const result = await fetch(`/${model}`, {\n method: \"DELETE\",\n query: {\n ...(where.length > 0 ? { $filter: filter } : {}),\n $top: 1,\n },\n });\n if (result.error) {\n throw new Error(\"Failed to delete record\");\n }\n },\n deleteMany: async ({ model, where }) => {\n const filter = parseWhere(where);\n logger.debug(\n where\n .map((o) => `typeof ${o.value} is ${typeof o.value}`)\n .join(\"\\n\"),\n );\n logger.debug(\"$filter\", filter);\n\n const result = await fetch(`/${model}/$count`, {\n method: \"DELETE\",\n query: {\n ...(where.length > 0 ? { $filter: filter } : {}),\n },\n output: z.coerce.number(),\n });\n if (result.error) {\n throw new Error(\"Failed to delete record\");\n }\n return result.data ?? 0;\n },\n update: async ({ model, where, update }) => {\n const result = await fetch(`/${model}`, {\n method: \"PATCH\",\n query: {\n ...(where.length > 0 ? { $filter: parseWhere(where) } : {}),\n $top: 1,\n $select: [`\"id\"`],\n },\n body: update,\n output: z.object({ value: z.array(z.any()) }),\n });\n return result.data?.value?.[0] ?? null;\n },\n updateMany: async ({ model, where, update }) => {\n const filter = parseWhere(where);\n const result = await fetch(`/${model}`, {\n method: \"PATCH\",\n query: {\n ...(where.length > 0 ? { $filter: filter } : {}),\n },\n body: update,\n });\n return result.data as any;\n },\n };\n },\n });\n};\n"],"names":[],"mappings":";;;;AASA,MAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,WAAW,EAAE,QAAQ,EAAE,SAAS;AAAA,EAChC,WAAW,EAAE,QAAQ,EAAE,SAAS;AAAA,EAChC,OAAO,EAAE,OAAO;AAAA,IACd,WAAW,EAAE,IAAI;AAAA,IACjB,MAAM,EAAE,MAAM;AAAA,MACZ,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,GAAG,UAAU,EAAE,OAAO,GAAG;AAAA,MACvD,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAA,EAAU,CAAA;AAAA,IAAA,CAChC;AAAA,IACD,UAAU,EAAE,OAAO,EAAE,SAAS,QAAQ;AAAA,EACvC,CAAA;AACH,CAAC;AAsBD,MAAM,gBAAkD;AAAA,EACtD,WAAW;AAAA,EACX,WAAW;AAAA,EACX,OAAO;AAAA,IACL,WAAW;AAAA,IACX,MAAM,EAAE,UAAU,IAAI,UAAU,GAAG;AAAA,IACnC,UAAU;AAAA,EAAA;AAEd;AAQO,SAAS,WAAW,OAAgC;AACzD,MAAI,CAAC,SAAS,MAAM,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SAAS,OAAA,IAAW,CAAA;AAAA,YAC/C;AAAA,YACA,MAAM;AAAA,UAAA,CACP;AACD,iBAAO,OAAO;AAAA,QAAA;AAAA,MAElB;AAAA,IAAA;AAAA,EACF,CACD;AACH;"}
|
|
1
|
+
{"version":3,"file":"adapter.js","sources":["../../src/adapter.ts"],"sourcesContent":["/** biome-ignore-all lint/suspicious/noExplicitAny: library code */\nimport { logger } from \"better-auth\";\nimport { type AdapterDebugLogs, type CleanedWhere, createAdapter } from \"better-auth/adapters\";\nimport buildQuery from \"odata-query\";\nimport { prettifyError, z } from \"zod/v4\";\nimport { createRawFetch, type FmOdataConfig } from \"./odata\";\n\nconst configSchema = z.object({\n debugLogs: z.unknown().optional(),\n usePlural: z.boolean().optional(),\n odata: z.object({\n serverUrl: z.url(),\n auth: z.union([z.object({ username: z.string(), password: z.string() }), z.object({ apiKey: z.string() })]),\n database: z.string().endsWith(\".fmp12\"),\n }),\n});\n\ninterface FileMakerAdapterConfig {\n /**\n * Helps you debug issues with the adapter.\n */\n debugLogs?: AdapterDebugLogs;\n /**\n * If the table names in the schema are plural.\n */\n usePlural?: boolean;\n\n /**\n * Connection details for the FileMaker server.\n */\n odata: FmOdataConfig;\n}\n\nexport interface AdapterOptions {\n config: FileMakerAdapterConfig;\n}\n\nconst defaultConfig: Required<FileMakerAdapterConfig> = {\n debugLogs: false,\n usePlural: false,\n odata: {\n serverUrl: \"\",\n auth: { username: \"\", password: \"\" },\n database: \"\",\n },\n};\n\n// Regex patterns for field validation and ISO date detection\nconst FIELD_SPECIAL_CHARS_REGEX = /[\\s_]/;\nconst ISO_DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?Z?$/;\n\n/**\n * Parse the where clause to an OData filter string.\n * @param where - The where clause to parse.\n * @returns The OData filter string.\n * @internal\n */\nexport function parseWhere(where?: CleanedWhere[]): string {\n if (!where || where.length === 0) {\n return \"\";\n }\n\n // Helper to quote field names with special chars or if field is 'id'\n function quoteField(field: string, value?: any) {\n // Never quote for null or date values (per test expectations)\n if (value === null || value instanceof Date) {\n return field;\n }\n // Always quote if field is 'id' or has space or underscore\n if (field === \"id\" || FIELD_SPECIAL_CHARS_REGEX.test(field)) {\n return `\"${field}\"`;\n }\n return field;\n }\n\n // Helper to format values for OData\n function formatValue(value: any): string {\n if (value === null) {\n return \"null\";\n }\n if (typeof value === \"boolean\") {\n return value ? \"true\" : \"false\";\n }\n if (value instanceof Date) {\n return value.toISOString();\n }\n if (Array.isArray(value)) {\n return `(${value.map(formatValue).join(\",\")})`;\n }\n\n // Handle strings - check if it's an ISO date string first\n if (typeof value === \"string\") {\n // Check if it's an ISO date string (YYYY-MM-DDTHH:mm:ss.sssZ format)\n if (ISO_DATE_REGEX.test(value)) {\n return value; // Return ISO date strings without quotes\n }\n return `'${value.replace(/'/g, \"''\")}'`; // Regular strings get quotes\n }\n\n return value?.toString() ?? \"\";\n }\n\n // Map our operators to OData\n const opMap: Record<string, string> = {\n eq: \"eq\",\n ne: \"ne\",\n lt: \"lt\",\n lte: \"le\",\n gt: \"gt\",\n gte: \"ge\",\n };\n\n // Build each clause\n const clauses: string[] = [];\n for (let i = 0; i < where.length; i++) {\n const cond = where[i];\n if (!cond) {\n continue;\n }\n const field = quoteField(cond.field, cond.value);\n let clause = \"\";\n switch (cond.operator) {\n case \"eq\":\n case \"ne\":\n case \"lt\":\n case \"lte\":\n case \"gt\":\n case \"gte\":\n clause = `${field} ${opMap[cond.operator]} ${formatValue(cond.value)}`;\n break;\n case \"in\":\n if (Array.isArray(cond.value)) {\n clause = cond.value.map((v) => `${field} eq ${formatValue(v)}`).join(\" or \");\n clause = `(${clause})`;\n }\n break;\n case \"contains\":\n clause = `contains(${field}, ${formatValue(cond.value)})`;\n break;\n case \"starts_with\":\n clause = `startswith(${field}, ${formatValue(cond.value)})`;\n break;\n case \"ends_with\":\n clause = `endswith(${field}, ${formatValue(cond.value)})`;\n break;\n default:\n clause = `${field} eq ${formatValue(cond.value)}`;\n }\n clauses.push(clause);\n // Add connector if not last\n if (i < where.length - 1) {\n clauses.push((cond.connector || \"and\").toLowerCase());\n }\n }\n return clauses.join(\" \");\n}\n\nexport const FileMakerAdapter = (_config: FileMakerAdapterConfig = defaultConfig) => {\n const parsed = configSchema.loose().safeParse(_config);\n\n if (!parsed.success) {\n throw new Error(`Invalid configuration: ${prettifyError(parsed.error)}`);\n }\n const config = parsed.data;\n\n const { fetch } = createRawFetch({\n ...config.odata,\n logging: config.debugLogs ? \"verbose\" : \"none\",\n });\n\n return createAdapter({\n config: {\n adapterId: \"filemaker\",\n adapterName: \"FileMaker\",\n usePlural: config.usePlural ?? false, // Whether the table names in the schema are plural.\n debugLogs: config.debugLogs ?? false, // Whether to enable debug logs.\n supportsJSON: false, // Whether the database supports JSON. (Default: false)\n supportsDates: false, // Whether the database supports dates. (Default: true)\n supportsBooleans: false, // Whether the database supports booleans. (Default: true)\n supportsNumericIds: false, // Whether the database supports auto-incrementing numeric IDs. (Default: true)\n },\n adapter: () => {\n return {\n create: async ({ data, model }) => {\n if (model === \"session\") {\n console.log(\"session\", data);\n }\n\n const result = await fetch(`/${model}`, {\n method: \"POST\",\n body: data,\n output: z.looseObject({ id: z.string() }),\n });\n\n if (result.error) {\n throw new Error(\"Failed to create record\");\n }\n\n return result.data as any;\n },\n count: async ({ model, where }) => {\n const filter = parseWhere(where);\n logger.debug(\"$filter\", filter);\n\n const query = buildQuery({\n filter: filter.length > 0 ? filter : undefined,\n });\n\n const result = await fetch(`/${model}/$count${query}`, {\n method: \"GET\",\n output: z.object({ value: z.number() }),\n });\n if (!result.data) {\n throw new Error(\"Failed to count records\");\n }\n return (result.data?.value as any) ?? 0;\n },\n findOne: async ({ model, where }) => {\n const filter = parseWhere(where);\n logger.debug(\"$filter\", filter);\n\n const query = buildQuery({\n top: 1,\n filter: filter.length > 0 ? filter : undefined,\n });\n\n const result = await fetch(`/${model}${query}`, {\n method: \"GET\",\n output: z.object({ value: z.array(z.any()) }),\n });\n if (result.error) {\n throw new Error(\"Failed to find record\");\n }\n return (result.data?.value?.[0] as any) ?? null;\n },\n findMany: async ({ model, where, limit, offset, sortBy }) => {\n const filter = parseWhere(where);\n logger.debug(\"FIND MANY\", { where, filter });\n\n const query = buildQuery({\n top: limit,\n skip: offset,\n orderBy: sortBy ? `${sortBy.field} ${sortBy.direction ?? \"asc\"}` : undefined,\n filter: filter.length > 0 ? filter : undefined,\n });\n logger.debug(\"QUERY\", query);\n\n const result = await fetch(`/${model}${query}`, {\n method: \"GET\",\n output: z.object({ value: z.array(z.any()) }),\n });\n logger.debug(\"RESULT\", result);\n\n if (result.error) {\n throw new Error(\"Failed to find records\");\n }\n\n return (result.data?.value as any) ?? [];\n },\n delete: async ({ model, where }) => {\n const filter = parseWhere(where);\n console.log(\"DELETE\", { model, where, filter });\n logger.debug(\"$filter\", filter);\n\n // Find a single id matching the filter\n const query = buildQuery({\n top: 1,\n select: [`\"id\"`],\n filter: filter.length > 0 ? filter : undefined,\n });\n\n const toDelete = await fetch(`/${model}${query}`, {\n method: \"GET\",\n output: z.object({ value: z.array(z.object({ id: z.string() })) }),\n });\n\n const id = toDelete.data?.value?.[0]?.id;\n if (!id) {\n // Nothing to delete\n return;\n }\n\n const result = await fetch(`/${model}('${id}')`, {\n method: \"DELETE\",\n });\n if (result.error) {\n console.log(\"DELETE ERROR\", result.error);\n throw new Error(\"Failed to delete record\");\n }\n },\n deleteMany: async ({ model, where }) => {\n const filter = parseWhere(where);\n console.log(\"DELETE MANY\", { model, where, filter });\n\n // Find all ids matching the filter\n const query = buildQuery({\n select: [`\"id\"`],\n filter: filter.length > 0 ? filter : undefined,\n });\n\n const rows = await fetch(`/${model}${query}`, {\n method: \"GET\",\n output: z.object({ value: z.array(z.object({ id: z.string() })) }),\n });\n\n const ids = rows.data?.value?.map((r: any) => r.id) ?? [];\n let deleted = 0;\n for (const id of ids) {\n const res = await fetch(`/${model}('${id}')`, {\n method: \"DELETE\",\n });\n if (!res.error) {\n deleted++;\n }\n }\n return deleted;\n },\n update: async ({ model, where, update }) => {\n const filter = parseWhere(where);\n logger.debug(\"UPDATE\", { model, where, update });\n logger.debug(\"$filter\", filter);\n // Find one id to update\n const query = buildQuery({\n select: [`\"id\"`],\n filter: filter.length > 0 ? filter : undefined,\n });\n\n const existing = await fetch(`/${model}${query}`, {\n method: \"GET\",\n output: z.object({ value: z.array(z.object({ id: z.string() })) }),\n });\n logger.debug(\"EXISTING\", existing.data);\n\n const id = existing.data?.value?.[0]?.id;\n if (!id) {\n return null;\n }\n\n const patchRes = await fetch(`/${model}('${id}')`, {\n method: \"PATCH\",\n body: update,\n });\n logger.debug(\"PATCH RES\", patchRes.data);\n if (patchRes.error) {\n return null;\n }\n\n // Read back the updated record\n const readBack = await fetch(`/${model}('${id}')`, {\n method: \"GET\",\n output: z.record(z.string(), z.unknown()),\n });\n logger.debug(\"READ BACK\", readBack.data);\n return (readBack.data as any) ?? null;\n },\n updateMany: async ({ model, where, update }) => {\n const filter = parseWhere(where);\n // Find all ids matching the filter\n const query = buildQuery({\n select: [`\"id\"`],\n filter: filter.length > 0 ? filter : undefined,\n });\n\n const rows = await fetch(`/${model}${query}`, {\n method: \"GET\",\n output: z.object({ value: z.array(z.object({ id: z.string() })) }),\n });\n\n const ids = rows.data?.value?.map((r: any) => r.id) ?? [];\n let updated = 0;\n for (const id of ids) {\n const res = await fetch(`/${model}('${id}')`, {\n method: \"PATCH\",\n body: update,\n });\n if (!res.error) {\n updated++;\n }\n }\n return updated as any;\n },\n };\n },\n });\n};\n"],"names":[],"mappings":";;;;;AAOA,MAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,WAAW,EAAE,QAAQ,EAAE,SAAS;AAAA,EAChC,WAAW,EAAE,QAAQ,EAAE,SAAS;AAAA,EAChC,OAAO,EAAE,OAAO;AAAA,IACd,WAAW,EAAE,IAAI;AAAA,IACjB,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,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ACD;AACH;"}
|
|
@@ -1,16 +1,8 @@
|
|
|
1
1
|
function addSvelteKitEnvModules(aliases) {
|
|
2
|
-
aliases["$env/dynamic/private"] = createDataUriModule(
|
|
3
|
-
|
|
4
|
-
);
|
|
5
|
-
aliases["$env/
|
|
6
|
-
createDynamicEnvModule()
|
|
7
|
-
);
|
|
8
|
-
aliases["$env/static/private"] = createDataUriModule(
|
|
9
|
-
createStaticEnvModule(filterPrivateEnv("PUBLIC_", ""))
|
|
10
|
-
);
|
|
11
|
-
aliases["$env/static/public"] = createDataUriModule(
|
|
12
|
-
createStaticEnvModule(filterPublicEnv("PUBLIC_", ""))
|
|
13
|
-
);
|
|
2
|
+
aliases["$env/dynamic/private"] = createDataUriModule(createDynamicEnvModule());
|
|
3
|
+
aliases["$env/dynamic/public"] = createDataUriModule(createDynamicEnvModule());
|
|
4
|
+
aliases["$env/static/private"] = createDataUriModule(createStaticEnvModule(filterPrivateEnv("PUBLIC_", "")));
|
|
5
|
+
aliases["$env/static/public"] = createDataUriModule(createStaticEnvModule(filterPublicEnv("PUBLIC_", "")));
|
|
14
6
|
}
|
|
15
7
|
function createDataUriModule(module) {
|
|
16
8
|
return `data:text/javascript;charset=utf-8,${encodeURIComponent(module)}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"add-svelte-kit-env-modules.js","sources":["../../../../src/better-auth-cli/utils/add-svelte-kit-env-modules.ts"],"sourcesContent":["export function addSvelteKitEnvModules(aliases: Record<string, string>) {\n
|
|
1
|
+
{"version":3,"file":"add-svelte-kit-env-modules.js","sources":["../../../../src/better-auth-cli/utils/add-svelte-kit-env-modules.ts"],"sourcesContent":["export function addSvelteKitEnvModules(aliases: Record<string, string>) {\n aliases[\"$env/dynamic/private\"] = createDataUriModule(createDynamicEnvModule());\n aliases[\"$env/dynamic/public\"] = createDataUriModule(createDynamicEnvModule());\n aliases[\"$env/static/private\"] = createDataUriModule(createStaticEnvModule(filterPrivateEnv(\"PUBLIC_\", \"\")));\n aliases[\"$env/static/public\"] = createDataUriModule(createStaticEnvModule(filterPublicEnv(\"PUBLIC_\", \"\")));\n}\n\nfunction createDataUriModule(module: string) {\n return `data:text/javascript;charset=utf-8,${encodeURIComponent(module)}`;\n}\n\nfunction createStaticEnvModule(env: Record<string, string>) {\n const declarations = Object.keys(env)\n .filter((k) => validIdentifier.test(k) && !reserved.has(k))\n .map((k) => `export const ${k} = ${JSON.stringify(env[k])};`);\n\n return `\n ${declarations.join(\"\\n\")}\n // jiti dirty hack: .unknown\n `;\n}\n\nfunction createDynamicEnvModule() {\n return `\n export const env = process.env;\n // jiti dirty hack: .unknown\n `;\n}\n\nexport function filterPrivateEnv(publicPrefix: string, privatePrefix: string) {\n return Object.fromEntries(\n Object.entries(process.env).filter(\n ([k]) => k.startsWith(privatePrefix) && (publicPrefix === \"\" || !k.startsWith(publicPrefix)),\n ),\n ) as Record<string, string>;\n}\n\nexport function filterPublicEnv(publicPrefix: string, privatePrefix: string) {\n return Object.fromEntries(\n Object.entries(process.env).filter(\n ([k]) => k.startsWith(publicPrefix) && (privatePrefix === \"\" || !k.startsWith(privatePrefix)),\n ),\n ) as Record<string, string>;\n}\n\nconst validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\nconst reserved = new Set([\n \"do\",\n \"if\",\n \"in\",\n \"for\",\n \"let\",\n \"new\",\n \"try\",\n \"var\",\n \"case\",\n \"else\",\n \"enum\",\n \"eval\",\n \"null\",\n \"this\",\n \"true\",\n \"void\",\n \"with\",\n \"await\",\n \"break\",\n \"catch\",\n \"class\",\n \"const\",\n \"false\",\n \"super\",\n \"throw\",\n \"while\",\n \"yield\",\n \"delete\",\n \"export\",\n \"import\",\n \"public\",\n \"return\",\n \"static\",\n \"switch\",\n \"typeof\",\n \"default\",\n \"extends\",\n \"finally\",\n \"package\",\n \"private\",\n \"continue\",\n \"debugger\",\n \"function\",\n \"arguments\",\n \"interface\",\n \"protected\",\n \"implements\",\n \"instanceof\",\n]);\n"],"names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,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;"}
|
|
@@ -1,19 +1,12 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import path from "path";
|
|
4
|
-
import babelPresetTypeScript from "@babel/preset-typescript";
|
|
1
|
+
import fs, { existsSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
5
3
|
import babelPresetReact from "@babel/preset-react";
|
|
6
|
-
import
|
|
4
|
+
import babelPresetTypeScript from "@babel/preset-typescript";
|
|
5
|
+
import { logger, BetterAuthError } from "better-auth";
|
|
6
|
+
import { loadConfig } from "c12";
|
|
7
7
|
import { addSvelteKitEnvModules } from "./add-svelte-kit-env-modules.js";
|
|
8
8
|
import { getTsconfigInfo } from "./get-tsconfig-info.js";
|
|
9
|
-
let possiblePaths = [
|
|
10
|
-
"auth.ts",
|
|
11
|
-
"auth.tsx",
|
|
12
|
-
"auth.js",
|
|
13
|
-
"auth.jsx",
|
|
14
|
-
"auth.server.js",
|
|
15
|
-
"auth.server.ts"
|
|
16
|
-
];
|
|
9
|
+
let possiblePaths = ["auth.ts", "auth.tsx", "auth.js", "auth.jsx", "auth.server.js", "auth.server.ts"];
|
|
17
10
|
possiblePaths = [
|
|
18
11
|
...possiblePaths,
|
|
19
12
|
...possiblePaths.map((it) => `lib/server/${it}`),
|
|
@@ -82,13 +75,15 @@ async function getConfig({
|
|
|
82
75
|
let configFile = null;
|
|
83
76
|
if (configPath) {
|
|
84
77
|
let resolvedPath = path.join(cwd, configPath);
|
|
85
|
-
if (existsSync(configPath))
|
|
78
|
+
if (existsSync(configPath)) {
|
|
79
|
+
resolvedPath = configPath;
|
|
80
|
+
}
|
|
86
81
|
const { config } = await loadConfig({
|
|
87
82
|
configFile: resolvedPath,
|
|
88
83
|
dotenv: true,
|
|
89
84
|
jitiOptions: jitiOptions(cwd)
|
|
90
85
|
});
|
|
91
|
-
if (!config.auth
|
|
86
|
+
if (!(config.auth || config.default)) {
|
|
92
87
|
if (shouldThrowOnError) {
|
|
93
88
|
throw new Error(
|
|
94
89
|
`Couldn't read your auth config in ${resolvedPath}. Make sure to default export your auth instance or to export as a variable named auth.`
|
|
@@ -127,9 +122,7 @@ async function getConfig({
|
|
|
127
122
|
break;
|
|
128
123
|
}
|
|
129
124
|
} catch (e) {
|
|
130
|
-
if (typeof e === "object" && e && "message" in e && typeof e.message === "string" && e.message.includes(
|
|
131
|
-
"This module cannot be imported from a Client Component module"
|
|
132
|
-
)) {
|
|
125
|
+
if (typeof e === "object" && e && "message" in e && typeof e.message === "string" && e.message.includes("This module cannot be imported from a Client Component module")) {
|
|
133
126
|
if (shouldThrowOnError) {
|
|
134
127
|
throw new Error(
|
|
135
128
|
`Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`
|
|
@@ -150,9 +143,7 @@ async function getConfig({
|
|
|
150
143
|
}
|
|
151
144
|
return configFile;
|
|
152
145
|
} catch (e) {
|
|
153
|
-
if (typeof e === "object" && e && "message" in e && typeof e.message === "string" && e.message.includes(
|
|
154
|
-
"This module cannot be imported from a Client Component module"
|
|
155
|
-
)) {
|
|
146
|
+
if (typeof e === "object" && e && "message" in e && typeof e.message === "string" && e.message.includes("This module cannot be imported from a Client Component module")) {
|
|
156
147
|
if (shouldThrowOnError) {
|
|
157
148
|
throw new Error(
|
|
158
149
|
`Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-config.js","sources":["../../../../src/better-auth-cli/utils/get-config.ts"],"sourcesContent":["import { loadConfig } from \"c12\";\nimport type { BetterAuthOptions } from \"better-auth\";\nimport { logger } from \"better-auth\";\nimport path from \"path\";\n// @ts-expect-error not typed\nimport babelPresetTypeScript from \"@babel/preset-typescript\";\n// @ts-expect-error not typed\nimport babelPresetReact from \"@babel/preset-react\";\nimport fs, { existsSync } from \"fs\";\nimport { BetterAuthError } from \"better-auth\";\nimport { addSvelteKitEnvModules } from \"./add-svelte-kit-env-modules\";\nimport { getTsconfigInfo } from \"./get-tsconfig-info\";\n\nlet possiblePaths = [\n \"auth.ts\",\n \"auth.tsx\",\n \"auth.js\",\n \"auth.jsx\",\n \"auth.server.js\",\n \"auth.server.ts\",\n];\n\npossiblePaths = [\n ...possiblePaths,\n ...possiblePaths.map((it) => `lib/server/${it}`),\n ...possiblePaths.map((it) => `server/${it}`),\n ...possiblePaths.map((it) => `lib/${it}`),\n ...possiblePaths.map((it) => `utils/${it}`),\n];\npossiblePaths = [\n ...possiblePaths,\n ...possiblePaths.map((it) => `src/${it}`),\n ...possiblePaths.map((it) => `app/${it}`),\n];\n\nfunction getPathAliases(cwd: string): Record<string, string> | null {\n const tsConfigPath = path.join(cwd, \"tsconfig.json\");\n if (!fs.existsSync(tsConfigPath)) {\n return null;\n }\n try {\n const tsConfig = getTsconfigInfo(cwd);\n const { paths = {}, baseUrl = \".\" } = tsConfig.compilerOptions || {};\n const result: Record<string, string> = {};\n const obj = Object.entries(paths) as [string, string[]][];\n for (const [alias, aliasPaths] of obj) {\n for (const aliasedPath of aliasPaths) {\n const resolvedBaseUrl = path.join(cwd, baseUrl);\n const finalAlias = alias.slice(-1) === \"*\" ? alias.slice(0, -1) : alias;\n const finalAliasedPath =\n aliasedPath.slice(-1) === \"*\"\n ? aliasedPath.slice(0, -1)\n : aliasedPath;\n\n result[finalAlias || \"\"] = path.join(resolvedBaseUrl, finalAliasedPath);\n }\n }\n addSvelteKitEnvModules(result);\n return result;\n } catch (error) {\n console.error(error);\n throw new BetterAuthError(\"Error parsing tsconfig.json\");\n }\n}\n/**\n * .tsx files are not supported by Jiti.\n */\nconst jitiOptions = (cwd: string) => {\n const alias = getPathAliases(cwd) || {};\n return {\n transformOptions: {\n babel: {\n presets: [\n [\n babelPresetTypeScript,\n {\n isTSX: true,\n allExtensions: true,\n },\n ],\n [babelPresetReact, { runtime: \"automatic\" }],\n ],\n },\n },\n extensions: [\".ts\", \".tsx\", \".js\", \".jsx\"],\n alias,\n };\n};\nexport async function getConfig({\n cwd,\n configPath,\n shouldThrowOnError = false,\n}: {\n cwd: string;\n configPath?: string;\n shouldThrowOnError?: boolean;\n}) {\n try {\n let configFile: BetterAuthOptions | null = null;\n if (configPath) {\n let resolvedPath: string = path.join(cwd, configPath);\n if (existsSync(configPath)) resolvedPath = configPath; // If the configPath is a file, use it as is, as it means the path wasn't relative.\n const { config } = await loadConfig<{\n auth: {\n options: BetterAuthOptions;\n };\n default?: {\n options: BetterAuthOptions;\n };\n }>({\n configFile: resolvedPath,\n dotenv: true,\n jitiOptions: jitiOptions(cwd),\n });\n if (!config.auth && !config.default) {\n if (shouldThrowOnError) {\n throw new Error(\n `Couldn't read your auth config in ${resolvedPath}. Make sure to default export your auth instance or to export as a variable named auth.`,\n );\n }\n logger.error(\n `[#better-auth]: Couldn't read your auth config in ${resolvedPath}. Make sure to default export your auth instance or to export as a variable named auth.`,\n );\n process.exit(1);\n }\n configFile = config.auth?.options || config.default?.options || null;\n }\n\n if (!configFile) {\n for (const possiblePath of possiblePaths) {\n try {\n const { config } = await loadConfig<{\n auth: {\n options: BetterAuthOptions;\n };\n default?: {\n options: BetterAuthOptions;\n };\n }>({\n configFile: possiblePath,\n jitiOptions: jitiOptions(cwd),\n });\n const hasConfig = Object.keys(config).length > 0;\n if (hasConfig) {\n configFile =\n config.auth?.options || config.default?.options || null;\n if (!configFile) {\n if (shouldThrowOnError) {\n throw new Error(\n \"Couldn't read your auth config. Make sure to default export your auth instance or to export as a variable named auth.\",\n );\n }\n logger.error(\"[#better-auth]: Couldn't read your auth config.\");\n console.log(\"\");\n logger.info(\n \"[#better-auth]: Make sure to default export your auth instance or to export as a variable named auth.\",\n );\n process.exit(1);\n }\n break;\n }\n } catch (e) {\n if (\n typeof e === \"object\" &&\n e &&\n \"message\" in e &&\n typeof e.message === \"string\" &&\n e.message.includes(\n \"This module cannot be imported from a Client Component module\",\n )\n ) {\n if (shouldThrowOnError) {\n throw new Error(\n `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`,\n );\n }\n logger.error(\n `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`,\n );\n process.exit(1);\n }\n if (shouldThrowOnError) {\n throw e;\n }\n logger.error(\"[#better-auth]: Couldn't read your auth config.\", e);\n process.exit(1);\n }\n }\n }\n return configFile;\n } catch (e) {\n if (\n typeof e === \"object\" &&\n e &&\n \"message\" in e &&\n typeof e.message === \"string\" &&\n e.message.includes(\n \"This module cannot be imported from a Client Component module\",\n )\n ) {\n if (shouldThrowOnError) {\n throw new Error(\n `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`,\n );\n }\n logger.error(\n `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`,\n );\n process.exit(1);\n }\n if (shouldThrowOnError) {\n throw e;\n }\n\n logger.error(\"Couldn't read your auth config.\", e);\n process.exit(1);\n }\n}\n\nexport { possiblePaths };\n"],"names":[],"mappings":";;;;;;;;AAaA,IAAI,gBAAgB;AAAA,EAClB;AAAA,EACA;AAAA,EACA;A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th-cli/utils/get-config.ts"],"sourcesContent":["import fs, { existsSync } from \"node:fs\";\nimport path from \"node:path\";\n// @ts-expect-error not typed\nimport babelPresetReact from \"@babel/preset-react\";\n// @ts-expect-error not typed\nimport babelPresetTypeScript from \"@babel/preset-typescript\";\nimport type { BetterAuthOptions } from \"better-auth\";\nimport { BetterAuthError, logger } from \"better-auth\";\nimport { loadConfig } from \"c12\";\nimport { addSvelteKitEnvModules } from \"./add-svelte-kit-env-modules\";\nimport { getTsconfigInfo } from \"./get-tsconfig-info\";\n\nlet possiblePaths = [\"auth.ts\", \"auth.tsx\", \"auth.js\", \"auth.jsx\", \"auth.server.js\", \"auth.server.ts\"];\n\npossiblePaths = [\n ...possiblePaths,\n ...possiblePaths.map((it) => `lib/server/${it}`),\n ...possiblePaths.map((it) => `server/${it}`),\n ...possiblePaths.map((it) => `lib/${it}`),\n ...possiblePaths.map((it) => `utils/${it}`),\n];\npossiblePaths = [\n ...possiblePaths,\n ...possiblePaths.map((it) => `src/${it}`),\n ...possiblePaths.map((it) => `app/${it}`),\n];\n\nfunction getPathAliases(cwd: string): Record<string, string> | null {\n const tsConfigPath = path.join(cwd, \"tsconfig.json\");\n if (!fs.existsSync(tsConfigPath)) {\n return null;\n }\n try {\n const tsConfig = getTsconfigInfo(cwd);\n const { paths = {}, baseUrl = \".\" } = tsConfig.compilerOptions || {};\n const result: Record<string, string> = {};\n const obj = Object.entries(paths) as [string, string[]][];\n for (const [alias, aliasPaths] of obj) {\n for (const aliasedPath of aliasPaths) {\n const resolvedBaseUrl = path.join(cwd, baseUrl);\n const finalAlias = alias.slice(-1) === \"*\" ? alias.slice(0, -1) : alias;\n const finalAliasedPath = aliasedPath.slice(-1) === \"*\" ? aliasedPath.slice(0, -1) : aliasedPath;\n\n result[finalAlias || \"\"] = path.join(resolvedBaseUrl, finalAliasedPath);\n }\n }\n addSvelteKitEnvModules(result);\n return result;\n } catch (error) {\n console.error(error);\n throw new BetterAuthError(\"Error parsing tsconfig.json\");\n }\n}\n/**\n * .tsx files are not supported by Jiti.\n */\nconst jitiOptions = (cwd: string) => {\n const alias = getPathAliases(cwd) || {};\n return {\n transformOptions: {\n babel: {\n presets: [\n [\n babelPresetTypeScript,\n {\n isTSX: true,\n allExtensions: true,\n },\n ],\n [babelPresetReact, { runtime: \"automatic\" }],\n ],\n },\n },\n extensions: [\".ts\", \".tsx\", \".js\", \".jsx\"],\n alias,\n };\n};\nexport async function getConfig({\n cwd,\n configPath,\n shouldThrowOnError = false,\n}: {\n cwd: string;\n configPath?: string;\n shouldThrowOnError?: boolean;\n}) {\n try {\n let configFile: BetterAuthOptions | null = null;\n if (configPath) {\n let resolvedPath: string = path.join(cwd, configPath);\n if (existsSync(configPath)) {\n resolvedPath = configPath; // If the configPath is a file, use it as is, as it means the path wasn't relative.\n }\n const { config } = await loadConfig<{\n auth: {\n options: BetterAuthOptions;\n };\n default?: {\n options: BetterAuthOptions;\n };\n }>({\n configFile: resolvedPath,\n dotenv: true,\n jitiOptions: jitiOptions(cwd),\n });\n if (!(config.auth || config.default)) {\n if (shouldThrowOnError) {\n throw new Error(\n `Couldn't read your auth config in ${resolvedPath}. Make sure to default export your auth instance or to export as a variable named auth.`,\n );\n }\n logger.error(\n `[#better-auth]: Couldn't read your auth config in ${resolvedPath}. Make sure to default export your auth instance or to export as a variable named auth.`,\n );\n process.exit(1);\n }\n configFile = config.auth?.options || config.default?.options || null;\n }\n\n if (!configFile) {\n for (const possiblePath of possiblePaths) {\n try {\n const { config } = await loadConfig<{\n auth: {\n options: BetterAuthOptions;\n };\n default?: {\n options: BetterAuthOptions;\n };\n }>({\n configFile: possiblePath,\n jitiOptions: jitiOptions(cwd),\n });\n const hasConfig = Object.keys(config).length > 0;\n if (hasConfig) {\n configFile = config.auth?.options || config.default?.options || null;\n if (!configFile) {\n if (shouldThrowOnError) {\n throw new Error(\n \"Couldn't read your auth config. Make sure to default export your auth instance or to export as a variable named auth.\",\n );\n }\n logger.error(\"[#better-auth]: Couldn't read your auth config.\");\n console.log(\"\");\n logger.info(\n \"[#better-auth]: Make sure to default export your auth instance or to export as a variable named auth.\",\n );\n process.exit(1);\n }\n break;\n }\n } catch (e) {\n if (\n typeof e === \"object\" &&\n e &&\n \"message\" in e &&\n typeof e.message === \"string\" &&\n e.message.includes(\"This module cannot be imported from a Client Component module\")\n ) {\n if (shouldThrowOnError) {\n throw new Error(\n `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`,\n );\n }\n logger.error(\n `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`,\n );\n process.exit(1);\n }\n if (shouldThrowOnError) {\n throw e;\n }\n logger.error(\"[#better-auth]: Couldn't read your auth config.\", e);\n process.exit(1);\n }\n }\n }\n return configFile;\n } catch (e) {\n if (\n typeof e === \"object\" &&\n e &&\n \"message\" in e &&\n typeof e.message === \"string\" &&\n e.message.includes(\"This module cannot be imported from a Client Component module\")\n ) {\n if (shouldThrowOnError) {\n throw new Error(\n `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`,\n );\n }\n logger.error(\n `Please remove import 'server-only' from your auth config file temporarily. The CLI cannot resolve the configuration with it included. You can re-add it after running the CLI.`,\n );\n process.exit(1);\n }\n if (shouldThrowOnError) {\n throw e;\n }\n\n logger.error(\"Couldn't read your auth config.\", e);\n process.exit(1);\n }\n}\n\nexport { possiblePaths };\n"],"names":[],"mappings":";;;;;;;;AAYA,IAAI,gBAAgB,CAAC,WAAW,YAAY,WAAW,YAAY,kBAAkB,gBAAgB;AAErG,gBAAgB;AAAA,EACd,GAAG;AAAA,EACH,GAAG,cAAc,IAAI,CAAC,OAAO,cAAc,EAAE,EAAE;AAAA,EAC/C,GAAG,cAAc,IAAI,CAAC,OAAO,UAAU,EAAE,EAAE;AAAA,EAC3C,GAAG,cAAc,IAAI,CAAC,OAAO,OAAO,EAAE,EAAE;AAAA,EACxC,GAA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,sBAAQ,IAAI,EAAE;AACP,qBAAA;AAAA,gBACL;AAAA,cACF;AACA,sBAAQ,KAAK,CAAC;AAAA,YAAA;AAEhB;AAAA,UAAA;AAAA,iBAEK,GAAG;AACV,cACE,OAAO,MAAM,YACb,KACA,aAAa,KACb,OAAO,EAAE,YAAY,YACrB,EAAE,QAAQ,SAAS,+DAA+D,GAClF;AACA,gBAAI,oBAAoB;AACtB,oBAAM,IAAI;AAAA,gBACR;AAAA,cACF;AAAA,YAAA;AAEK,mBAAA;AAAA,cACL;AAAA,YACF;AACA,oBAAQ,KAAK,CAAC;AAAA,UAAA;AAEhB,cAAI,oBAAoB;AAChB,kBAAA;AAAA,UAAA;AAED,iBAAA,MAAM,mDAAmD,CAAC;AACjE,kBAAQ,KAAK,CAAC;AAAA,QAAA;AAAA,MAChB;AAAA,IACF;AAEK,WAAA;AAAA,WACA,GAAG;AACV,QACE,OAAO,MAAM,YACb,KACA,aAAa,KACb,OAAO,EAAE,YAAY,YACrB,EAAE,QAAQ,SAAS,+DAA+D,GAClF;AACA,UAAI,oBAAoB;AACtB,cAAM,IAAI;AAAA,UACR;AAAA,QACF;AAAA,MAAA;AAEK,aAAA;AAAA,QACL;AAAA,MACF;AACA,cAAQ,KAAK,CAAC;AAAA,IAAA;AAEhB,QAAI,oBAAoB;AAChB,YAAA;AAAA,IAAA;AAGD,WAAA,MAAM,mCAAmC,CAAC;AACjD,YAAQ,KAAK,CAAC;AAAA,EAAA;AAElB;"}
|
|
@@ -1,22 +1,15 @@
|
|
|
1
|
-
import path from "path";
|
|
1
|
+
import path from "node:path";
|
|
2
2
|
import fs from "fs-extra";
|
|
3
3
|
function stripJsonComments(jsonString) {
|
|
4
|
-
return jsonString.replace(
|
|
5
|
-
/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g,
|
|
6
|
-
(m, g) => g ? "" : m
|
|
7
|
-
).replace(/,(?=\s*[}\]])/g, "");
|
|
4
|
+
return jsonString.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m).replace(/,(?=\s*[}\]])/g, "");
|
|
8
5
|
}
|
|
9
6
|
function getTsconfigInfo(cwd, flatPath) {
|
|
10
7
|
let tsConfigPath;
|
|
11
8
|
{
|
|
12
9
|
tsConfigPath = cwd ? path.join(cwd, "tsconfig.json") : path.join("tsconfig.json");
|
|
13
10
|
}
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
return JSON.parse(stripJsonComments(text));
|
|
17
|
-
} catch (error) {
|
|
18
|
-
throw error;
|
|
19
|
-
}
|
|
11
|
+
const text = fs.readFileSync(tsConfigPath, "utf-8");
|
|
12
|
+
return JSON.parse(stripJsonComments(text));
|
|
20
13
|
}
|
|
21
14
|
export {
|
|
22
15
|
getTsconfigInfo,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-tsconfig-info.js","sources":["../../../../src/better-auth-cli/utils/get-tsconfig-info.ts"],"sourcesContent":["import path from \"path\";\nimport fs from \"fs-extra\";\n\nexport function stripJsonComments(jsonString: string): string {\n
|
|
1
|
+
{"version":3,"file":"get-tsconfig-info.js","sources":["../../../../src/better-auth-cli/utils/get-tsconfig-info.ts"],"sourcesContent":["import path from \"node:path\";\nimport fs from \"fs-extra\";\n\nexport function stripJsonComments(jsonString: string): string {\n return jsonString\n .replace(/\\\\\"|\"(?:\\\\\"|[^\"])*\"|(\\/\\/.*|\\/\\*[\\s\\S]*?\\*\\/)/g, (m, g) => (g ? \"\" : m))\n .replace(/,(?=\\s*[}\\]])/g, \"\");\n}\nexport function getTsconfigInfo(cwd?: string, flatPath?: string) {\n let tsConfigPath: string;\n if (flatPath) {\n tsConfigPath = flatPath;\n } else {\n tsConfigPath = cwd ? path.join(cwd, \"tsconfig.json\") : path.join(\"tsconfig.json\");\n }\n const text = fs.readFileSync(tsConfigPath, \"utf-8\");\n return JSON.parse(stripJsonComments(text));\n}\n"],"names":[],"mappings":";;AAGO,SAAS,kBAAkB,YAA4B;AAC5D,SAAO,WACJ,QAAQ,kDAAkD,CAAC,GAAG,MAAO,IAAI,KAAK,CAAE,EAChF,QAAQ,kBAAkB,EAAE;AACjC;AACgB,SAAA,gBAAgB,KAAc,UAAmB;AAC3D,MAAA;AAGG;AACU,mBAAA,MAAM,KAAK,KAAK,KAAK,eAAe,IAAI,KAAK,KAAK,eAAe;AAAA,EAAA;AAElF,QAAM,OAAO,GAAG,aAAa,cAAc,OAAO;AAClD,SAAO,KAAK,MAAM,kBAAkB,IAAI,CAAC;AAC3C;"}
|