@proofkit/better-auth 0.3.0 → 0.3.1-beta.1

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.
@@ -1,13 +1,12 @@
1
- import { CleanedWhere, AdapterDebugLogs } from 'better-auth/adapters';
1
+ import { CleanedWhere, DBAdapterDebugLogOption } from 'better-auth/adapters';
2
2
  import { FmOdataConfig } from './odata.js';
3
- interface FileMakerAdapterConfig {
4
- debugLogs?: AdapterDebugLogs;
3
+ export interface FileMakerAdapterConfig {
4
+ debugLogs?: DBAdapterDebugLogOption;
5
5
  usePlural?: boolean;
6
6
  odata: FmOdataConfig;
7
7
  }
8
- export type AdapterOptions = {
8
+ export interface AdapterOptions {
9
9
  config: FileMakerAdapterConfig;
10
- };
10
+ }
11
11
  export declare function parseWhere(where?: CleanedWhere[]): string;
12
- export declare const FileMakerAdapter: (_config?: FileMakerAdapterConfig) => (options: import('better-auth').BetterAuthOptions) => import('better-auth').Adapter;
13
- export {};
12
+ export declare const FileMakerAdapter: (_config?: FileMakerAdapterConfig) => import('better-auth/adapters').AdapterFactory;
@@ -1,17 +1,14 @@
1
- import { createAdapter } from "better-auth/adapters";
2
- import { createRawFetch } from "./odata/index.js";
3
- import { z, prettifyError } from "zod/v4";
4
1
  import { logger } from "better-auth";
2
+ import { createAdapter } from "better-auth/adapters";
5
3
  import buildQuery from "odata-query";
4
+ import { z, prettifyError } from "zod/v4";
5
+ import { createRawFetch } from "./odata/index.js";
6
6
  const configSchema = z.object({
7
7
  debugLogs: z.unknown().optional(),
8
8
  usePlural: z.boolean().optional(),
9
9
  odata: z.object({
10
10
  serverUrl: z.url(),
11
- auth: z.union([
12
- z.object({ username: z.string(), password: z.string() }),
13
- z.object({ apiKey: z.string() })
14
- ]),
11
+ auth: z.union([z.object({ username: z.string(), password: z.string() }), z.object({ apiKey: z.string() })]),
15
12
  database: z.string().endsWith(".fmp12")
16
13
  })
17
14
  });
@@ -24,21 +21,36 @@ const defaultConfig = {
24
21
  database: ""
25
22
  }
26
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?$/;
27
26
  function parseWhere(where) {
28
- if (!where || where.length === 0) return "";
27
+ if (!where || where.length === 0) {
28
+ return "";
29
+ }
29
30
  function quoteField(field, value) {
30
- if (value === null || value instanceof Date) return field;
31
- if (field === "id" || /[\s_]/.test(field)) return `"${field}"`;
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
+ }
32
37
  return field;
33
38
  }
34
39
  function formatValue(value) {
35
- if (value === null) return "null";
36
- if (typeof value === "boolean") return value ? "true" : "false";
37
- if (value instanceof Date) return value.toISOString();
38
- if (Array.isArray(value)) return `(${value.map(formatValue).join(",")})`;
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
+ }
39
52
  if (typeof value === "string") {
40
- const isoDateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z?$/;
41
- if (isoDateRegex.test(value)) {
53
+ if (ISO_DATE_REGEX.test(value)) {
42
54
  return value;
43
55
  }
44
56
  return `'${value.replace(/'/g, "''")}'`;
@@ -56,7 +68,9 @@ function parseWhere(where) {
56
68
  const clauses = [];
57
69
  for (let i = 0; i < where.length; i++) {
58
70
  const cond = where[i];
59
- if (!cond) continue;
71
+ if (!cond) {
72
+ continue;
73
+ }
60
74
  const field = quoteField(cond.field, cond.value);
61
75
  let clause = "";
62
76
  switch (cond.operator) {
@@ -103,7 +117,7 @@ const FileMakerAdapter = (_config = defaultConfig) => {
103
117
  ...config.odata,
104
118
  logging: config.debugLogs ? "verbose" : "none"
105
119
  });
106
- return createAdapter({
120
+ const adapterFactory = createAdapter({
107
121
  config: {
108
122
  adapterId: "filemaker",
109
123
  adapterName: "FileMaker",
@@ -120,10 +134,9 @@ const FileMakerAdapter = (_config = defaultConfig) => {
120
134
  supportsNumericIds: false
121
135
  // Whether the database supports auto-incrementing numeric IDs. (Default: true)
122
136
  },
123
- adapter: ({ options }) => {
137
+ adapter: () => {
124
138
  return {
125
- options: { config },
126
- create: async ({ data, model, select }) => {
139
+ create: async ({ data, model }) => {
127
140
  if (model === "session") {
128
141
  console.log("session", data);
129
142
  }
@@ -235,7 +248,9 @@ const FileMakerAdapter = (_config = defaultConfig) => {
235
248
  const res = await fetch(`/${model}('${id}')`, {
236
249
  method: "DELETE"
237
250
  });
238
- if (!res.error) deleted++;
251
+ if (!res.error) {
252
+ deleted++;
253
+ }
239
254
  }
240
255
  return deleted;
241
256
  },
@@ -254,13 +269,17 @@ const FileMakerAdapter = (_config = defaultConfig) => {
254
269
  });
255
270
  logger.debug("EXISTING", existing.data);
256
271
  const id = (_c = (_b = (_a = existing.data) == null ? void 0 : _a.value) == null ? void 0 : _b[0]) == null ? void 0 : _c.id;
257
- if (!id) return null;
272
+ if (!id) {
273
+ return null;
274
+ }
258
275
  const patchRes = await fetch(`/${model}('${id}')`, {
259
276
  method: "PATCH",
260
277
  body: update
261
278
  });
262
279
  logger.debug("PATCH RES", patchRes.data);
263
- if (patchRes.error) return null;
280
+ if (patchRes.error) {
281
+ return null;
282
+ }
264
283
  const readBack = await fetch(`/${model}('${id}')`, {
265
284
  method: "GET",
266
285
  output: z.record(z.string(), z.unknown())
@@ -286,13 +305,17 @@ const FileMakerAdapter = (_config = defaultConfig) => {
286
305
  method: "PATCH",
287
306
  body: update
288
307
  });
289
- if (!res.error) updated++;
308
+ if (!res.error) {
309
+ updated++;
310
+ }
290
311
  }
291
312
  return updated;
292
313
  }
293
314
  };
294
315
  }
295
316
  });
317
+ adapterFactory.filemakerConfig = config;
318
+ return adapterFactory;
296
319
  };
297
320
  export {
298
321
  FileMakerAdapter,
@@ -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 { createRawFetch, type FmOdataConfig } from \"./odata\";\nimport { prettifyError, z } from \"zod/v4\";\nimport { logger } from \"better-auth\";\nimport buildQuery from \"odata-query\";\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, baseURL } = 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: ({ 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\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\n ? `${sortBy.field} ${sortBy.direction ?? \"asc\"}`\n : 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) deleted++;\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) return null;\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) return null;\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) updated++;\n }\n return updated as any;\n },\n };\n },\n });\n};\n"],"names":[],"mappings":";;;;;AAUA,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;A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AA,CACzC;AACM,iBAAA,MAAM,aAAa,SAAS,IAAI;AACvC,iBAAQ,SAAS,QAAgB;AAAA,QACnC;AAAA,QACA,YAAY,OAAO,EAAE,OAAO,OAAO,aAAa;;AACxC,gBAAA,SAAS,WAAW,KAAK;AAE/B,gBAAM,QAAQ,WAAW;AAAA,YACvB,QAAQ,CAAC,MAAM;AAAA,YACf,QAAQ,OAAO,SAAS,IAAI,SAAS;AAAA,UAAA,CACtC;AAED,gBAAM,OAAO,MAAM,MAAM,IAAI,KAAK,GAAG,KAAK,IAAI;AAAA,YAC5C,QAAQ;AAAA,YACR,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,CAAC,EAAG,CAAA;AAAA,UAAA,CAClE;AAEK,gBAAA,QAAM,gBAAK,SAAL,mBAAW,UAAX,mBAAkB,IAAI,CAAC,MAAW,EAAE,QAAO,CAAC;AACxD,cAAI,UAAU;AACd,qBAAW,MAAM,KAAK;AACpB,kBAAM,MAAM,MAAM,MAAM,IAAI,KAAK,KAAK,EAAE,MAAM;AAAA,cAC5C,QAAQ;AAAA,cACR,MAAM;AAAA,YAAA,CACP;AACG,gBAAA,CAAC,IAAI,MAAO;AAAA,UAAA;AAEX,iBAAA;AAAA,QAAA;AAAA,MAEX;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 CleanedWhere, createAdapter, type DBAdapterDebugLogOption } 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\nexport interface FileMakerAdapterConfig {\n /**\n * Helps you debug issues with the adapter.\n */\n debugLogs?: DBAdapterDebugLogOption;\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 const adapterFactory = 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 // Expose the FileMaker config for CLI access\n (adapterFactory as any).filemakerConfig = config as FileMakerAdapterConfig;\n return adapterFactory;\n};\n"],"names":[],"mappings":";;;;;AAOA,MAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,WAAW,EAAE,QAAA,EAAU,SAAA;AAAA,EACvB,WAAW,EAAE,QAAA,EAAU,SAAA;AAAA,EACvB,OAAO,EAAE,OAAO;AAAA,IACd,WAAW,EAAE,IAAA;AAAA,IACb,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,OAAA,GAAU,UAAU,EAAE,SAAO,CAAG,GAAG,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAO,CAAG,CAAC,CAAC;AAAA,IAC1G,UAAU,EAAE,OAAA,EAAS,SAAS,QAAQ;AAAA,EAAA,CACvC;AACH,CAAC;AAsBD,MAAM,gBAAkD;AAAA,EACtD,WAAW;AAAA,EACX,WAAW;AAAA,EACX,OAAO;AAAA,IACL,WAAW;AAAA,IACX,MAAM,EAAE,UAAU,IAAI,UAAU,GAAA;AAAA,IAChC,UAAU;AAAA,EAAA;AAEd;AAGA,MAAM,4BAA4B;AAClC,MAAM,iBAAiB;AAQhB,SAAS,WAAW,OAAgC;AACzD,MAAI,CAAC,SAAS,MAAM,W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OAAO,EAAE,OAAO,OAAO,aAAa;;AAC9C,gBAAM,SAAS,WAAW,KAAK;AAE/B,gBAAM,QAAQ,WAAW;AAAA,YACvB,QAAQ,CAAC,MAAM;AAAA,YACf,QAAQ,OAAO,SAAS,IAAI,SAAS;AAAA,UAAA,CACtC;AAED,gBAAM,OAAO,MAAM,MAAM,IAAI,KAAK,GAAG,KAAK,IAAI;AAAA,YAC5C,QAAQ;AAAA,YACR,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,OAAA,GAAU,CAAC,GAAG;AAAA,UAAA,CAClE;AAED,gBAAM,QAAM,gBAAK,SAAL,mBAAW,UAAX,mBAAkB,IAAI,CAAC,MAAW,EAAE,QAAO,CAAA;AACvD,cAAI,UAAU;AACd,qBAAW,MAAM,KAAK;AACpB,kBAAM,MAAM,MAAM,MAAM,IAAI,KAAK,KAAK,EAAE,MAAM;AAAA,cAC5C,QAAQ;AAAA,cACR,MAAM;AAAA,YAAA,CACP;AACD,gBAAI,CAAC,IAAI,OAAO;AACd;AAAA,YACF;AAAA,UACF;AACA,iBAAO;AAAA,QACT;AAAA,MAAA;AAAA,IAEJ;AAAA,EAAA,CACD;AAGA,iBAAuB,kBAAkB;AAC1C,SAAO;AACT;"}
@@ -1,16 +1,8 @@
1
1
  function addSvelteKitEnvModules(aliases) {
2
- aliases["$env/dynamic/private"] = createDataUriModule(
3
- createDynamicEnvModule()
4
- );
5
- aliases["$env/dynamic/public"] = createDataUriModule(
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\taliases[\"$env/dynamic/private\"] = createDataUriModule(\n\t\tcreateDynamicEnvModule(),\n\t);\n\taliases[\"$env/dynamic/public\"] = createDataUriModule(\n\t\tcreateDynamicEnvModule(),\n\t);\n\taliases[\"$env/static/private\"] = createDataUriModule(\n\t\tcreateStaticEnvModule(filterPrivateEnv(\"PUBLIC_\", \"\")),\n\t);\n\taliases[\"$env/static/public\"] = createDataUriModule(\n\t\tcreateStaticEnvModule(filterPublicEnv(\"PUBLIC_\", \"\")),\n\t);\n}\n\nfunction createDataUriModule(module: string) {\n\treturn `data:text/javascript;charset=utf-8,${encodeURIComponent(module)}`;\n}\n\nfunction createStaticEnvModule(env: Record<string, string>) {\n\tconst declarations = Object.keys(env)\n\t\t.filter((k) => validIdentifier.test(k) && !reserved.has(k))\n\t\t.map((k) => `export const ${k} = ${JSON.stringify(env[k])};`);\n\n\treturn `\n ${declarations.join(\"\\n\")}\n // jiti dirty hack: .unknown\n `;\n}\n\nfunction createDynamicEnvModule() {\n\treturn `\n export const env = process.env;\n // jiti dirty hack: .unknown\n `;\n}\n\nexport function filterPrivateEnv(publicPrefix: string, privatePrefix: string) {\n\treturn Object.fromEntries(\n\t\tObject.entries(process.env).filter(\n\t\t\t([k]) =>\n\t\t\t\tk.startsWith(privatePrefix) &&\n\t\t\t\t(publicPrefix === \"\" || !k.startsWith(publicPrefix)),\n\t\t),\n\t) as Record<string, string>;\n}\n\nexport function filterPublicEnv(publicPrefix: string, privatePrefix: string) {\n\treturn Object.fromEntries(\n\t\tObject.entries(process.env).filter(\n\t\t\t([k]) =>\n\t\t\t\tk.startsWith(publicPrefix) &&\n\t\t\t\t(privatePrefix === \"\" || !k.startsWith(privatePrefix)),\n\t\t),\n\t) as Record<string, string>;\n}\n\nconst validIdentifier = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\nconst reserved = new Set([\n\t\"do\",\n\t\"if\",\n\t\"in\",\n\t\"for\",\n\t\"let\",\n\t\"new\",\n\t\"try\",\n\t\"var\",\n\t\"case\",\n\t\"else\",\n\t\"enum\",\n\t\"eval\",\n\t\"null\",\n\t\"this\",\n\t\"true\",\n\t\"void\",\n\t\"with\",\n\t\"await\",\n\t\"break\",\n\t\"catch\",\n\t\"class\",\n\t\"const\",\n\t\"false\",\n\t\"super\",\n\t\"throw\",\n\t\"while\",\n\t\"yield\",\n\t\"delete\",\n\t\"export\",\n\t\"import\",\n\t\"public\",\n\t\"return\",\n\t\"static\",\n\t\"switch\",\n\t\"typeof\",\n\t\"default\",\n\t\"extends\",\n\t\"finally\",\n\t\"package\",\n\t\"private\",\n\t\"continue\",\n\t\"debugger\",\n\t\"function\",\n\t\"arguments\",\n\t\"interface\",\n\t\"protected\",\n\t\"implements\",\n\t\"instanceof\",\n]);\n"],"names":[],"mappings":"AAAO,SAAS,uBAAuB,SAAiC;AACvE,UAAQ,sBAAsB,IAAI;AAAA,IACjC,uBAAuB;AAAA,EACxB;AACA,UAAQ,qBAAqB,IAAI;AAAA,IAChC,uBAAuB;AAAA,EACxB;AACA,UAAQ,qBAAqB,IAAI;AAAA,IAChC,sBAAsB,iBAAiB,WAAW,EAAE,CAAC;AAAA,EACtD;AACA,UAAQ,oBAAoB,IAAI;AAAA,IAC/B,sBAAsB,gBAAgB,WAAW,EAAE,CAAC;AAAA,EACrD;AACD;AAEA,SAAS,oBAAoB,QAAgB;AACrC,SAAA,sCAAsC,mBAAmB,MAAM,CAAC;AACxE;AAEA,SAAS,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ACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,CAAC;"}
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":[],"mappings":"AAAO,SAAS,uBAAuB,SAAiC;AACtE,UAAQ,sBAAsB,IAAI,oBAAoB,uBAAA,CAAwB;AAC9E,UAAQ,qBAAqB,IAAI,oBAAoB,uBAAA,CAAwB;AAC7E,UAAQ,qBAAqB,IAAI,oBAAoB,sBAAsB,iBAAiB,WAAW,EAAE,CAAC,CAAC;AAC3G,UAAQ,oBAAoB,IAAI,oBAAoB,sBAAsB,gBAAgB,WAAW,EAAE,CAAC,CAAC;AAC3G;AAEA,SAAS,oBAAoB,QAAgB;AAC3C,SAAO,sCAAsC,mBAAmB,MAAM,CAAC;AACzE;AAEA,SAAS,sBAAsB,KAA6B;AAC1D,QAAM,eAAe,OAAO,KAAK,GAAG,EACjC,OAAO,CAAC,MAAM,gBAAgB,KAAK,CAAC,KAAK,CAAC,SAAS,IAAI,CAAC,CAAC,EACzD,IAAI,CAAC,MAAM,gBAAgB,CAAC,MAAM,KAAK,UAAU,IAAI,CAAC,CAAC,CAAC,GAAG;AAE9D,SAAO;AAAA,IACL,aAAa,KAAK,IAAI,CAAC;AAAA;AAAA;AAG3B;AAEA,SAAS,yBAAyB;AAChC,SAAO;AAAA;AAAA;AAAA;AAIT;AAEO,SAAS,iBAAiB,cAAsB,eAAuB;AAC5E,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,QAAQ,GAAG,EAAE;AAAA,MAC1B,CAAC,CAAC,CAAC,MAAM,EAAE,WAAW,aAAa,KAA6B,CAAC,EAAE,WAAW,YAAY;AAAA,IAAA;AAAA,EAC5F;AAEJ;AAEO,SAAS,gBAAgB,cAAsB,eAAuB;AAC3E,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,QAAQ,GAAG,EAAE;AAAA,MAC1B,CAAC,CAAC,CAAC,MAAM,EAAE,WAAW,YAAY,KAAM,kBAAkB;AAAA,IAAiC;AAAA,EAC7F;AAEJ;AAEA,MAAM,kBAAkB;AACxB,MAAM,+BAAe,IAAI;AAAA,EACvB;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;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;"}
@@ -1,19 +1,12 @@
1
- import { loadConfig } from "c12";
2
- import { logger, BetterAuthError } from "better-auth";
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 fs, { existsSync } from "fs";
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)) resolvedPath = 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 && !config.default) {
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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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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Q,IAAI,EAAE;AACd,qBAAO;AAAA,gBACL;AAAA,cAAA;AAEF,sBAAQ,KAAK,CAAC;AAAA,YAChB;AACA;AAAA,UACF;AAAA,QACF,SAAS,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,cAAA;AAAA,YAEJ;AACA,mBAAO;AAAA,cACL;AAAA,YAAA;AAEF,oBAAQ,KAAK,CAAC;AAAA,UAChB;AACA,cAAI,oBAAoB;AACtB,kBAAM;AAAA,UACR;AACA,iBAAO,MAAM,mDAAmD,CAAC;AACjE,kBAAQ,KAAK,CAAC;AAAA,QAChB;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT,SAAS,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,QAAA;AAAA,MAEJ;AACA,aAAO;AAAA,QACL;AAAA,MAAA;AAEF,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,QAAI,oBAAoB;AACtB,YAAM;AAAA,IACR;AAEA,WAAO,MAAM,mCAAmC,CAAC;AACjD,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;"}
@@ -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
- try {
15
- const text = fs.readFileSync(tsConfigPath, "utf-8");
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\treturn jsonString\n\t\t.replace(/\\\\\"|\"(?:\\\\\"|[^\"])*\"|(\\/\\/.*|\\/\\*[\\s\\S]*?\\*\\/)/g, (m, g) =>\n\t\t\tg ? \"\" : m,\n\t\t)\n\t\t.replace(/,(?=\\s*[}\\]])/g, \"\");\n}\nexport function getTsconfigInfo(cwd?: string, flatPath?: string) {\n\tlet tsConfigPath: string;\n\tif (flatPath) {\n\t\ttsConfigPath = flatPath;\n\t} else {\n\t\ttsConfigPath = cwd\n\t\t\t? path.join(cwd, \"tsconfig.json\")\n\t\t\t: path.join(\"tsconfig.json\");\n\t}\n\ttry {\n\t\tconst text = fs.readFileSync(tsConfigPath, \"utf-8\");\n\t\treturn JSON.parse(stripJsonComments(text));\n\t} catch (error) {\n\t\tthrow error;\n\t}\n}\n"],"names":[],"mappings":";;AAGO,SAAS,kBAAkB,YAA4B;AAC7D,SAAO,WACL;AAAA,IAAQ;AAAA,IAAkD,CAAC,GAAG,MAC9D,IAAI,KAAK;AAAA,EAAA,EAET,QAAQ,kBAAkB,EAAE;AAC/B;AACgB,SAAA,gBAAgB,KAAc,UAAmB;AAC5D,MAAA;AAGG;AACS,mBAAA,MACZ,KAAK,KAAK,KAAK,eAAe,IAC9B,KAAK,KAAK,eAAe;AAAA,EAAA;AAEzB,MAAA;AACH,UAAM,OAAO,GAAG,aAAa,cAAc,OAAO;AAClD,WAAO,KAAK,MAAM,kBAAkB,IAAI,CAAC;AAAA,WACjC,OAAO;AACT,UAAA;AAAA,EAAA;AAER;"}
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;AACO,SAAS,gBAAgB,KAAc,UAAmB;AAC/D,MAAI;AAGG;AACL,mBAAe,MAAM,KAAK,KAAK,KAAK,eAAe,IAAI,KAAK,KAAK,eAAe;AAAA,EAClF;AACA,QAAM,OAAO,GAAG,aAAa,cAAc,OAAO;AAClD,SAAO,KAAK,MAAM,kBAAkB,IAAI,CAAC;AAC3C;"}
@@ -1,21 +1,17 @@
1
1
  #!/usr/bin/env node --no-warnings
2
2
  import { Command } from "@commander-js/extra-typings";
3
- import fs from "fs-extra";
4
- import { planMigration, prettyPrintMigrationPlan, executeMigration } from "../migrate.js";
5
- import { getAdapter, getAuthTables } from "better-auth/db";
6
- import { getConfig } from "../better-auth-cli/utils/get-config.js";
7
3
  import { logger } from "better-auth";
8
- import prompts from "prompts";
4
+ import { getAdapter, getSchema } from "better-auth/db";
9
5
  import chalk from "chalk";
6
+ import fs from "fs-extra";
7
+ import prompts from "prompts";
8
+ import { getConfig } from "../better-auth-cli/utils/get-config.js";
9
+ import { planMigration, prettyPrintMigrationPlan, executeMigration } from "../migrate.js";
10
10
  import { createRawFetch } from "../odata/index.js";
11
11
  import "dotenv/config";
12
12
  async function main() {
13
13
  const program = new Command();
14
- program.command("migrate", { isDefault: true }).option(
15
- "--cwd <path>",
16
- "Path to the current working directory",
17
- process.cwd()
18
- ).option("--config <path>", "Path to the config file").option("-u, --username <username>", "Full Access Username").option("-p, --password <password>", "Full Access Password").option("-y, --yes", "Skip confirmation", false).action(async (options) => {
14
+ program.command("migrate", { isDefault: true }).option("--cwd <path>", "Path to the current working directory", process.cwd()).option("--config <path>", "Path to the config file").option("-u, --username <username>", "Full Access Username").option("-p, --password <password>", "Full Access Password").option("-y, --yes", "Skip confirmation", false).action(async (options) => {
19
15
  const cwd = options.cwd;
20
16
  if (!fs.existsSync(cwd)) {
21
17
  logger.error(`The directory "${cwd}" does not exist.`);
@@ -36,13 +32,11 @@ async function main() {
36
32
  process.exit(1);
37
33
  });
38
34
  if (adapter.id !== "filemaker") {
39
- logger.error(
40
- "This generator is only compatible with the FileMaker adapter."
41
- );
35
+ logger.error("This generator is only compatible with the FileMaker adapter.");
42
36
  return;
43
37
  }
44
- const betterAuthSchema = getAuthTables(config);
45
- const adapterConfig = adapter.options.config;
38
+ const betterAuthSchema = getSchema(config);
39
+ const adapterConfig = adapter.filemakerConfig;
46
40
  const { fetch } = createRawFetch({
47
41
  ...adapterConfig.odata,
48
42
  auth: (
@@ -55,11 +49,7 @@ async function main() {
55
49
  logging: "verbose"
56
50
  // Enable logging for CLI operations
57
51
  });
58
- const migrationPlan = await planMigration(
59
- fetch,
60
- betterAuthSchema,
61
- adapterConfig.odata.database
62
- );
52
+ const migrationPlan = await planMigration(fetch, betterAuthSchema, adapterConfig.odata.database);
63
53
  if (migrationPlan.length === 0) {
64
54
  logger.info("No changes to apply. Database is up to date.");
65
55
  return;
@@ -67,11 +57,7 @@ async function main() {
67
57
  if (!options.yes) {
68
58
  prettyPrintMigrationPlan(migrationPlan);
69
59
  if (migrationPlan.length > 0) {
70
- console.log(
71
- chalk.gray(
72
- "💡 Tip: You can use the --yes flag to skip this confirmation."
73
- )
74
- );
60
+ console.log(chalk.gray("💡 Tip: You can use the --yes flag to skip this confirmation."));
75
61
  }
76
62
  const { confirm } = await prompts({
77
63
  type: "confirm",
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../src/cli/index.ts"],"sourcesContent":["#!/usr/bin/env node --no-warnings\nimport { Command } from \"@commander-js/extra-typings\";\nimport fs from \"fs-extra\";\n\nimport {\n executeMigration,\n planMigration,\n prettyPrintMigrationPlan,\n} from \"../migrate\";\nimport { getAdapter, getAuthTables } from \"better-auth/db\";\nimport { getConfig } from \"../better-auth-cli/utils/get-config\";\nimport { logger } from \"better-auth\";\nimport prompts from \"prompts\";\nimport chalk from \"chalk\";\nimport { AdapterOptions } from \"../adapter\";\nimport { createRawFetch } from \"../odata\";\nimport \"dotenv/config\";\n\nasync function main() {\n const program = new Command();\n\n program\n .command(\"migrate\", { isDefault: true })\n .option(\n \"--cwd <path>\",\n \"Path to the current working directory\",\n process.cwd(),\n )\n .option(\"--config <path>\", \"Path to the config file\")\n .option(\"-u, --username <username>\", \"Full Access Username\")\n .option(\"-p, --password <password>\", \"Full Access Password\")\n .option(\"-y, --yes\", \"Skip confirmation\", false)\n\n .action(async (options) => {\n const cwd = options.cwd;\n if (!fs.existsSync(cwd)) {\n logger.error(`The directory \"${cwd}\" does not exist.`);\n process.exit(1);\n }\n\n const config = await getConfig({\n cwd,\n configPath: options.config,\n });\n if (!config) {\n logger.error(\n \"No configuration file found. Add a `auth.ts` file to your project or pass the path to the configuration file using the `--config` flag.\",\n );\n return;\n }\n\n const adapter = await getAdapter(config).catch((e) => {\n logger.error(e.message);\n process.exit(1);\n });\n\n if (adapter.id !== \"filemaker\") {\n logger.error(\n \"This generator is only compatible with the FileMaker adapter.\",\n );\n return;\n }\n\n const betterAuthSchema = getAuthTables(config);\n\n const adapterConfig = (adapter.options as AdapterOptions).config;\n const { fetch } = createRawFetch({\n ...adapterConfig.odata,\n auth:\n // If the username and password are provided in the CLI, use them to authenticate instead of what's in the config file.\n options.username && options.password\n ? {\n username: options.username,\n password: options.password,\n }\n : adapterConfig.odata.auth,\n logging: \"verbose\", // Enable logging for CLI operations\n });\n\n const migrationPlan = await planMigration(\n fetch,\n betterAuthSchema,\n adapterConfig.odata.database,\n );\n\n if (migrationPlan.length === 0) {\n logger.info(\"No changes to apply. Database is up to date.\");\n return;\n }\n\n if (!options.yes) {\n prettyPrintMigrationPlan(migrationPlan);\n\n if (migrationPlan.length > 0) {\n console.log(\n chalk.gray(\n \"💡 Tip: You can use the --yes flag to skip this confirmation.\",\n ),\n );\n }\n\n const { confirm } = await prompts({\n type: \"confirm\",\n name: \"confirm\",\n message: \"Apply the above changes to your database?\",\n });\n if (!confirm) {\n logger.error(\"Schema changes not applied.\");\n return;\n }\n }\n\n await executeMigration(fetch, migrationPlan);\n\n logger.info(\"Migration applied successfully.\");\n });\n await program.parseAsync(process.argv);\n process.exit(0);\n}\n\nmain().catch(console.error);\n"],"names":[],"mappings":";;;;;;;;;;;AAkBA,eAAe,OAAO;AACd,QAAA,UAAU,IAAI,QAAQ;AAE5B,UACG,QAAQ,WAAW,EAAE,WAAW,KAAM,CAAA,EACtC;AAAA,IACC;AAAA,IACA;AAAA,IACA,QAAQ,IAAI;AAAA,EAAA,EAEb,OAAO,mBAAmB,yBAAyB,EACnD,OAAO,6BAA6B,sBAAsB,EAC1D,OAAO,6BAA6B,sBAAsB,EAC1D,OAAO,aAAa,qBAAqB,K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QAChC,MAAM;AAAA,QACN,MAAM;AAAA,QACN,SAAS;AAAA,MAAA,CACV;AACD,UAAI,CAAC,SAAS;AACZ,eAAO,MAAM,6BAA6B;AAC1C;AAAA,MAAA;AAAA,IACF;AAGI,UAAA,iBAAiB,OAAO,aAAa;AAE3C,WAAO,KAAK,iCAAiC;AAAA,EAAA,CAC9C;AACG,QAAA,QAAQ,WAAW,QAAQ,IAAI;AACrC,UAAQ,KAAK,CAAC;AAChB;AAEA,OAAO,MAAM,QAAQ,KAAK;"}
1
+ {"version":3,"file":"index.js","sources":["../../../src/cli/index.ts"],"sourcesContent":["#!/usr/bin/env node --no-warnings\nimport { Command } from \"@commander-js/extra-typings\";\nimport { logger } from \"better-auth\";\nimport { getAdapter, getSchema } from \"better-auth/db\";\nimport chalk from \"chalk\";\nimport fs from \"fs-extra\";\nimport prompts from \"prompts\";\nimport type { FileMakerAdapterConfig } from \"../adapter\";\nimport { getConfig } from \"../better-auth-cli/utils/get-config\";\nimport { executeMigration, planMigration, prettyPrintMigrationPlan } from \"../migrate\";\nimport { createRawFetch } from \"../odata\";\nimport \"dotenv/config\";\n\nasync function main() {\n const program = new Command();\n\n program\n .command(\"migrate\", { isDefault: true })\n .option(\"--cwd <path>\", \"Path to the current working directory\", process.cwd())\n .option(\"--config <path>\", \"Path to the config file\")\n .option(\"-u, --username <username>\", \"Full Access Username\")\n .option(\"-p, --password <password>\", \"Full Access Password\")\n .option(\"-y, --yes\", \"Skip confirmation\", false)\n\n .action(async (options) => {\n const cwd = options.cwd;\n if (!fs.existsSync(cwd)) {\n logger.error(`The directory \"${cwd}\" does not exist.`);\n process.exit(1);\n }\n\n const config = await getConfig({\n cwd,\n configPath: options.config,\n });\n if (!config) {\n logger.error(\n \"No configuration file found. Add a `auth.ts` file to your project or pass the path to the configuration file using the `--config` flag.\",\n );\n return;\n }\n\n const adapter = await getAdapter(config).catch((e) => {\n logger.error(e.message);\n process.exit(1);\n });\n\n if (adapter.id !== \"filemaker\") {\n logger.error(\"This generator is only compatible with the FileMaker adapter.\");\n return;\n }\n\n const betterAuthSchema = getSchema(config);\n\n const adapterConfig = (adapter as unknown as { filemakerConfig: FileMakerAdapterConfig }).filemakerConfig;\n const { fetch } = createRawFetch({\n ...adapterConfig.odata,\n auth:\n // If the username and password are provided in the CLI, use them to authenticate instead of what's in the config file.\n options.username && options.password\n ? {\n username: options.username,\n password: options.password,\n }\n : adapterConfig.odata.auth,\n logging: \"verbose\", // Enable logging for CLI operations\n });\n\n const migrationPlan = await planMigration(fetch, betterAuthSchema, adapterConfig.odata.database);\n\n if (migrationPlan.length === 0) {\n logger.info(\"No changes to apply. Database is up to date.\");\n return;\n }\n\n if (!options.yes) {\n prettyPrintMigrationPlan(migrationPlan);\n\n if (migrationPlan.length > 0) {\n console.log(chalk.gray(\"💡 Tip: You can use the --yes flag to skip this confirmation.\"));\n }\n\n const { confirm } = await prompts({\n type: \"confirm\",\n name: \"confirm\",\n message: \"Apply the above changes to your database?\",\n });\n if (!confirm) {\n logger.error(\"Schema changes not applied.\");\n return;\n }\n }\n\n await executeMigration(fetch, migrationPlan);\n\n logger.info(\"Migration applied successfully.\");\n });\n await program.parseAsync(process.argv);\n process.exit(0);\n}\n\nmain().catch(console.error);\n"],"names":[],"mappings":";;;;;;;;;;;AAaA,eAAe,OAAO;AACpB,QAAM,UAAU,IAAI,QAAA;AAEpB,UACG,QAAQ,WAAW,EAAE,WAAW,MAAM,EACtC,OAAO,gBAAgB,yCAAyC,QAAQ,IAAA,CAAK,EAC7E,OAAO,mBAAmB,yBAAyB,EACnD,OAAO,6BAA6B,sBAAsB,EAC1D,OAAO,6BAA6B,sBAAsB,EAC1D,OAAO,aAAa,qBAAqB,KAAK,EAE9C,OAAO,OAAO,YAAY;AACzB,UAAM,MAAM,QAAQ;AACpB,QAAI,CAAC,GAAG,WAAW,GAAG,GAAG;AACvB,aAAO,MAAM,kBAAkB,GAAG,mBAAmB;AACrD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAEA,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QAAQ,WAAW,QAAQ,IAAI;AACrC,UAAQ,KAAK,CAAC;AAChB;AAEA,OAAO,MAAM,QAAQ,KAAK;"}
@@ -1,9 +1,13 @@
1
- import { BetterAuthDbSchema } from 'better-auth/db';
1
+ import { DBFieldAttribute } from 'better-auth/db';
2
2
  import { Metadata } from 'fm-odata-client';
3
3
  import { default as z } from 'zod/v4';
4
4
  import { createRawFetch } from './odata.js';
5
+ type BetterAuthSchema = Record<string, {
6
+ fields: Record<string, DBFieldAttribute>;
7
+ order: number;
8
+ }>;
5
9
  export declare function getMetadata(fetch: ReturnType<typeof createRawFetch>["fetch"], databaseName: string): Promise<Metadata | null>;
6
- export declare function planMigration(fetch: ReturnType<typeof createRawFetch>["fetch"], betterAuthSchema: BetterAuthDbSchema, databaseName: string): Promise<MigrationPlan>;
10
+ export declare function planMigration(fetch: ReturnType<typeof createRawFetch>["fetch"], betterAuthSchema: BetterAuthSchema, databaseName: string): Promise<MigrationPlan>;
7
11
  export declare function executeMigration(fetch: ReturnType<typeof createRawFetch>["fetch"], migrationPlan: MigrationPlan): Promise<void>;
8
12
  declare const migrationPlanSchema: z.ZodArray<z.ZodObject<{
9
13
  tableName: z.ZodString;
@@ -78,7 +82,7 @@ declare const migrationPlanSchema: z.ZodArray<z.ZodObject<{
78
82
  repetitions: z.ZodOptional<z.ZodNumber>;
79
83
  type: z.ZodLiteral<"container">;
80
84
  externalSecurePath: z.ZodOptional<z.ZodString>;
81
- }, z.core.$strip>]>>;
85
+ }, z.core.$strip>], "type">>;
82
86
  }, z.core.$strip>>;
83
87
  export type MigrationPlan = z.infer<typeof migrationPlanSchema>;
84
88
  export declare function prettyPrintMigrationPlan(migrationPlan: MigrationPlan): void;