@prisma/orm-better-auth 0.0.0-stage → 8.0.0-rc.25-dev.2

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/index.mjs ADDED
@@ -0,0 +1,1188 @@
1
+ import { getAuthTables } from "@better-auth/core/db";
2
+ import { createAdapterFactory } from "@better-auth/core/db/adapter";
3
+ import { BetterAuthError } from "@better-auth/core/error";
4
+ import { blindCast } from "@prisma/orm-framework/utils/casts";
5
+ import { UNBOUND_DOMAIN_NAMESPACE_ID } from "@prisma/orm-framework/contract/default-namespace";
6
+ import * as internal from "@better-auth/core/db/internal";
7
+ import { resolveStorageTable } from "@prisma/orm-family-sql/contract/resolve-storage-table";
8
+ import { all, and, or } from "@prisma/orm-family-sql/orm-client";
9
+ //#region src/models/identifiers.ts
10
+ const pslIdentifier = /^[A-Za-z_][A-Za-z0-9_]*$/;
11
+ function isPslIdentifier(name) {
12
+ return pslIdentifier.test(name);
13
+ }
14
+ /** The message for a Better Auth model name that is not a Prisma identifier, or `undefined` when it is one. */
15
+ function invalidModelNameMessage(name) {
16
+ if (isPslIdentifier(name)) return void 0;
17
+ return `Better Auth's model name "${name}" is not a valid Prisma model name: use letters, digits and "_", not starting with a digit. Rename the model with Better Auth's "modelName" option.`;
18
+ }
19
+ /** The message for a Better Auth field name that is not a Prisma identifier, or `undefined` when it is one. */
20
+ function invalidFieldNameMessage(model, field) {
21
+ if (isPslIdentifier(field)) return void 0;
22
+ return `Better Auth's field name "${field}" of model "${model}" is not a valid Prisma field name: use letters, digits and "_", not starting with a digit. Rename the field with Better Auth's "fields" option.`;
23
+ }
24
+ /** The message for Better Auth models whose names differ only in the case of the first letter. */
25
+ function caseOnlyNameCollisionMessage(names) {
26
+ const quoted = names.map((name) => `"${name}"`);
27
+ return `Better Auth's models ${`${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}`} have names that differ only in the case of the first letter, which this adapter does not support. Set a different "modelName" on all but one of them in your Better Auth configuration.`;
28
+ }
29
+ function assertModelName(name) {
30
+ const message = invalidModelNameMessage(name);
31
+ if (message !== void 0) throw new BetterAuthError(message);
32
+ }
33
+ function assertFieldName(model, field) {
34
+ const message = invalidFieldNameMessage(model, field);
35
+ if (message !== void 0) throw new BetterAuthError(message);
36
+ }
37
+ function upperFirst(name) {
38
+ return name.charAt(0).toUpperCase() + name.slice(1);
39
+ }
40
+ function lowerFirst(name) {
41
+ return name.charAt(0).toLowerCase() + name.slice(1);
42
+ }
43
+ //#endregion
44
+ //#region src/models/model-lookup.ts
45
+ function missingModelMessage(physicalName) {
46
+ return `Model "${physicalName}" is not in your Prisma contract. Run \`npx auth@latest generate\` to see what to add.`;
47
+ }
48
+ function ambiguousModelMessage(name, namespaceIds) {
49
+ return `Model "${name}" is in more than one namespace of your Prisma contract (${namespaceIds.join(", ")}). Set the adapter's "namespace" option.`;
50
+ }
51
+ /**
52
+ * Finds the contract model for a Better Auth physical model name: the exact name first, then the name with its first letter upper-cased, in the namespace the adapter's `namespace` option names or else in every namespace. The physical model name is matched to a contract model name, never to a table name.
53
+ */
54
+ function findModel(contract, physicalName, namespace) {
55
+ const namespaces = contract.domain.namespaces;
56
+ const searched = namespace === void 0 ? Object.keys(namespaces) : [namespace].filter((id) => Object.hasOwn(namespaces, id));
57
+ const candidates = [.../* @__PURE__ */ new Set([physicalName, upperFirst(physicalName)])];
58
+ for (const name of candidates) {
59
+ const hits = searched.filter((id) => Object.hasOwn(namespaces[id]?.models ?? {}, name)).sort();
60
+ const [only] = hits;
61
+ if (hits.length > 1) return {
62
+ kind: "ambiguous",
63
+ name,
64
+ namespaceIds: hits
65
+ };
66
+ const model = only === void 0 ? void 0 : namespaces[only]?.models[name];
67
+ if (only !== void 0 && model !== void 0) return {
68
+ kind: "found",
69
+ name,
70
+ namespaceId: only,
71
+ model
72
+ };
73
+ }
74
+ return { kind: "missing" };
75
+ }
76
+ //#endregion
77
+ //#region src/orm.ts
78
+ const collectionMethods = [
79
+ "where",
80
+ "select",
81
+ "orderBy",
82
+ "limit",
83
+ "offset",
84
+ "include",
85
+ "first",
86
+ "all",
87
+ "aggregate",
88
+ "create",
89
+ "update",
90
+ "updateAndCount",
91
+ "deleteAndCount"
92
+ ];
93
+ function isOrmCollection(value) {
94
+ return typeof value === "object" && value !== null && collectionMethods.every((method) => typeof Reflect.get(value, method) === "function");
95
+ }
96
+ /** A property of an ORM client proxy, read by run-time name. */
97
+ function property(target, name) {
98
+ return typeof target === "object" && target !== null ? Reflect.get(target, name) : void 0;
99
+ }
100
+ /** Calls a method of an ORM client object by run-time name, or returns `undefined` when it has none. */
101
+ function callMethod(target, name, ...args) {
102
+ const method = property(target, name);
103
+ if (typeof method !== "function") return void 0;
104
+ return Reflect.apply(method, target, args);
105
+ }
106
+ function hasMethod(target, name) {
107
+ return typeof property(target, name) === "function";
108
+ }
109
+ /** A filter built by calling the ORM client's field and `fns` methods by run-time name. */
110
+ function asCondition(value) {
111
+ return blindCast(value);
112
+ }
113
+ //#endregion
114
+ //#region src/collections.ts
115
+ /** Finds each model once per adapter instance, and its collection on the ORM client root a call uses. */
116
+ function createModelCollections(contract, namespace) {
117
+ const found = /* @__PURE__ */ new Map();
118
+ const namespaceIds = Object.keys(contract.domain.namespaces);
119
+ const flat = namespaceIds.length === 1 && namespaceIds[0] === UNBOUND_DOMAIN_NAMESPACE_ID;
120
+ return {
121
+ model(physicalName) {
122
+ const known = found.get(physicalName);
123
+ if (known !== void 0) return known;
124
+ assertModelName(physicalName);
125
+ const lookup = findModel(contract, physicalName, namespace);
126
+ if (lookup.kind === "ambiguous") throw new BetterAuthError(ambiguousModelMessage(lookup.name, lookup.namespaceIds));
127
+ if (lookup.kind === "missing") throw new BetterAuthError(missingModelMessage(physicalName));
128
+ found.set(physicalName, lookup);
129
+ return lookup;
130
+ },
131
+ collection(orm, model) {
132
+ const collection = property(flat ? orm : property(orm, model.namespaceId), model.name);
133
+ if (!isOrmCollection(collection)) throw new BetterAuthError(missingModelMessage(model.name));
134
+ return collection;
135
+ }
136
+ };
137
+ }
138
+ //#endregion
139
+ //#region src/models/better-auth-models.ts
140
+ function physicalName(modelName, usePlural) {
141
+ return usePlural ? `${modelName}s` : modelName;
142
+ }
143
+ function isOmitted(key, table, options) {
144
+ if (table.disableMigrations === true) return true;
145
+ return key === "session" && options.secondaryStorage !== void 0 && options.session?.storeSessionInDatabase !== true;
146
+ }
147
+ function referencedTable(tables, model) {
148
+ return tables[model] ?? Object.values(tables).find((table) => table.modelName === model);
149
+ }
150
+ function resolveReference(tables, references, usePlural) {
151
+ const table = referencedTable(tables, references.model);
152
+ const field = table?.fields[references.field];
153
+ return {
154
+ model: physicalName(table?.modelName ?? references.model, usePlural),
155
+ field: field?.fieldName || references.field,
156
+ onDelete: references.onDelete ?? "cascade"
157
+ };
158
+ }
159
+ /**
160
+ * The models Better Auth's table description names, one per physical model name, in Better Auth's table order. The adapter serves calls for all of them.
161
+ */
162
+ function betterAuthModels(tables, { betterAuthOptions, usePlural }) {
163
+ const merged = /* @__PURE__ */ new Map();
164
+ for (const [key, table] of Object.entries(tables)) {
165
+ const name = physicalName(table.modelName, usePlural);
166
+ const model = merged.get(name) ?? {
167
+ fields: /* @__PURE__ */ new Map(),
168
+ indexes: [],
169
+ managed: false
170
+ };
171
+ model.managed ||= !isOmitted(key, table, betterAuthOptions);
172
+ merged.set(name, model);
173
+ for (const [fieldKey, attribute] of Object.entries(table.fields)) {
174
+ const fieldName = attribute.fieldName || fieldKey;
175
+ if (fieldName === "id") continue;
176
+ model.fields.set(fieldName, {
177
+ name: fieldName,
178
+ attribute,
179
+ reference: attribute.references === void 0 ? void 0 : resolveReference(tables, attribute.references, usePlural)
180
+ });
181
+ }
182
+ for (const index of table.indexes ?? []) model.indexes.push({
183
+ fields: index.fields.map((field) => table.fields[field]?.fieldName || field),
184
+ unique: index.unique === true
185
+ });
186
+ }
187
+ return [...merged].map(([name, { fields, indexes, managed }]) => ({
188
+ physicalName: name,
189
+ fields: [...fields.values()],
190
+ indexes,
191
+ managed
192
+ }));
193
+ }
194
+ /** Groups of physical model names that differ only in the case of the first letter, which the adapter refuses. */
195
+ function caseOnlyNameCollisions(models) {
196
+ const byModelName = /* @__PURE__ */ new Map();
197
+ for (const { physicalName } of models) {
198
+ const name = upperFirst(physicalName);
199
+ byModelName.set(name, [...byModelName.get(name) ?? [], physicalName]);
200
+ }
201
+ return [...byModelName.values()].filter((names) => names.length > 1);
202
+ }
203
+ /** The models of the schema Better Auth manages, which the comparison checks. */
204
+ function managedModels(tables, options) {
205
+ return betterAuthModels(tables, options).filter((model) => model.managed);
206
+ }
207
+ function idStrategyOf(options) {
208
+ const generateId = options.advanced?.database?.generateId;
209
+ if (generateId === "serial") return "serial";
210
+ if (generateId === "uuid") return "uuid";
211
+ if (generateId === false) return "contract";
212
+ return "string";
213
+ }
214
+ /** Better Auth can write `null` to any optional field: its default value replaces only a missing value on create, never an explicit `null`. So the contract must declare the field optional. */
215
+ function mayBeNull(attribute) {
216
+ return attribute.required === false;
217
+ }
218
+ function isIdReference(attribute) {
219
+ return attribute.references?.field === "id";
220
+ }
221
+ //#endregion
222
+ //#region src/models/codec-kinds.ts
223
+ const codecKinds = [
224
+ "string",
225
+ "enum",
226
+ "uuid",
227
+ "date",
228
+ "number",
229
+ "boolean",
230
+ "other"
231
+ ];
232
+ const codecIdsByKind = {
233
+ string: [
234
+ "pg/text@1",
235
+ "sql/varchar@1",
236
+ "sql/char@1",
237
+ "sqlite/text@1"
238
+ ],
239
+ enum: ["pg/enum@1"],
240
+ uuid: ["pg/uuid@1"],
241
+ date: [
242
+ "pg/timestamptz-date@1",
243
+ "pg/timestamp-date@1",
244
+ "sqlite/datetime@1"
245
+ ],
246
+ number: [
247
+ "pg/int2@1",
248
+ "pg/int4@1",
249
+ "pg/int8number@1",
250
+ "pg/float4@1",
251
+ "pg/float8@1",
252
+ "sqlite/integer@1",
253
+ "sqlite/real@1"
254
+ ],
255
+ boolean: ["pg/bool@1", "sqlite/boolean@1"],
256
+ other: [
257
+ "pg/int8@1",
258
+ "pg/unboundedint@1",
259
+ "pg/numeric@1",
260
+ "pg/timestamptz-temporal@1",
261
+ "pg/timestamptz-string@1",
262
+ "pg/timestamp-temporal@1",
263
+ "pg/timestamp-string@1",
264
+ "pg/timestamp-instant@1",
265
+ "pg/date-temporal@1",
266
+ "pg/date-string@1",
267
+ "pg/time-temporal@1",
268
+ "pg/time-string@1",
269
+ "pg/timetz@1",
270
+ "pg/inet@1",
271
+ "pg/interval@1",
272
+ "pg/interval-string@1",
273
+ "pg/bit@1",
274
+ "pg/varbit@1",
275
+ "pg/xml@1",
276
+ "pg/oid@1",
277
+ "pg/money@1",
278
+ "pg/json@1",
279
+ "pg/jsonb@1",
280
+ "pg/bytea@1",
281
+ "sqlite/bigint@1",
282
+ "sqlite/decimal@1",
283
+ "sqlite/datetime-temporal@1",
284
+ "sqlite/datetime-string@1",
285
+ "sqlite/date-string@1",
286
+ "sqlite/date-temporal@1",
287
+ "sqlite/time-string@1",
288
+ "sqlite/time-temporal@1",
289
+ "sqlite/duration-string@1",
290
+ "sqlite/json@1",
291
+ "sqlite/blob@1"
292
+ ]
293
+ };
294
+ const kindByCodecId = new Map(codecKinds.flatMap((kind) => codecIdsByKind[kind].map((id) => [id, kind])));
295
+ /** The kind of JavaScript value a codec reads and writes, or `undefined` for a codec this table does not know. */
296
+ function codecKind(codecId) {
297
+ return kindByCodecId.get(codecId);
298
+ }
299
+ //#endregion
300
+ //#region src/models/field-type.ts
301
+ /** What a contract field holds, as messages name it: its codec id, `<codec id> list`, `a value object` or `a union`. */
302
+ function describeFieldType(field) {
303
+ if (field.type.kind === "valueObject") return "a value object";
304
+ if (field.type.kind === "union") return "a union";
305
+ return field.many ? `${field.type.codecId} list` : field.type.codecId;
306
+ }
307
+ //#endregion
308
+ //#region src/contract/compare.ts
309
+ const acceptedKindsByIdStrategy = {
310
+ serial: ["number"],
311
+ uuid: ["string", "uuid"],
312
+ string: ["string"],
313
+ contract: ["string"]
314
+ };
315
+ const defaultNamespaceByTarget = { postgres: "public" };
316
+ function acceptedKinds(attribute, idStrategy) {
317
+ if (isIdReference(attribute)) return acceptedKindsByIdStrategy[idStrategy];
318
+ switch (attribute.type) {
319
+ case "number": return ["number"];
320
+ case "boolean": return ["boolean"];
321
+ case "date": return ["date"];
322
+ case "string": return ["string", "enum"];
323
+ default: return Array.isArray(attribute.type) ? ["string", "enum"] : ["string"];
324
+ }
325
+ }
326
+ /** The description of a contract field whose type Better Auth cannot use, or `undefined` when it can. */
327
+ function wrongTypeFound(field, accepted) {
328
+ if (field.type.kind !== "scalar" || field.many) return describeFieldType(field);
329
+ const kind = codecKind(field.type.codecId);
330
+ return kind === void 0 || accepted.includes(kind) ? void 0 : describeFieldType(field);
331
+ }
332
+ function isSqlModelStorage(storage) {
333
+ return typeof storage["table"] === "string" && typeof storage["namespaceId"] === "string";
334
+ }
335
+ function columnFacts(contract, found, field) {
336
+ const storage = found.model.storage;
337
+ if (!isSqlModelStorage(storage)) return {
338
+ hasDatabaseDefault: false,
339
+ hasCreateGenerator: false
340
+ };
341
+ const column = storage.fields[field]?.column ?? field;
342
+ return {
343
+ hasDatabaseDefault: (resolveStorageTable(contract.storage, storage.table, storage.namespaceId)?.table)?.columns[column]?.default !== void 0,
344
+ hasCreateGenerator: (contract.execution?.mutations.defaults ?? []).some(({ ref, onCreate }) => onCreate !== void 0 && ref.namespace === storage.namespaceId && ref.entry === storage.table && ref.field === column)
345
+ };
346
+ }
347
+ function compareFoundModel(contract, expected, found, idStrategy, problems) {
348
+ const fields = found.model.fields;
349
+ const model = found.name;
350
+ const missingFields = [];
351
+ const id = fields["id"];
352
+ if (id === void 0) missingFields.push("id");
353
+ else {
354
+ const wrong = wrongTypeFound(id, acceptedKindsByIdStrategy[idStrategy]);
355
+ if (wrong !== void 0) problems.push({
356
+ kind: "wrong-type",
357
+ model,
358
+ field: "id",
359
+ attribute: void 0,
360
+ reference: void 0,
361
+ found: wrong
362
+ });
363
+ const facts = columnFacts(contract, found, "id");
364
+ if ((idStrategy === "serial" || idStrategy === "contract") && !facts.hasDatabaseDefault && !facts.hasCreateGenerator) problems.push({
365
+ kind: "id-without-default",
366
+ model
367
+ });
368
+ }
369
+ for (const field of expected.fields) {
370
+ const contractField = fields[field.name];
371
+ if (contractField === void 0) {
372
+ missingFields.push(field.name);
373
+ continue;
374
+ }
375
+ const wrong = wrongTypeFound(contractField, acceptedKinds(field.attribute, idStrategy));
376
+ if (wrong !== void 0) problems.push({
377
+ kind: "wrong-type",
378
+ model,
379
+ field: field.name,
380
+ attribute: field.attribute,
381
+ reference: field.reference,
382
+ found: wrong
383
+ });
384
+ else if (mayBeNull(field.attribute) && !contractField.nullable) problems.push({
385
+ kind: "optional-field-not-nullable",
386
+ model,
387
+ field: field.name,
388
+ attribute: field.attribute,
389
+ reference: field.reference
390
+ });
391
+ }
392
+ for (const field of missingFields) problems.push({
393
+ kind: "missing-field",
394
+ model,
395
+ field
396
+ });
397
+ const written = /* @__PURE__ */ new Set(["id", ...expected.fields.map((field) => field.name)]);
398
+ for (const [name, field] of Object.entries(fields)) {
399
+ if (written.has(name) || field.nullable) continue;
400
+ const facts = columnFacts(contract, found, name);
401
+ if (!facts.hasDatabaseDefault && !facts.hasCreateGenerator) problems.push({
402
+ kind: "required-field-not-written",
403
+ model,
404
+ field: name
405
+ });
406
+ }
407
+ return missingFields;
408
+ }
409
+ function hasUuidId(found) {
410
+ const id = found.model.fields["id"];
411
+ return id?.type.kind === "scalar" && codecKind(id.type.codecId) === "uuid";
412
+ }
413
+ function uuidKeyedModelsOf(models, referencedModels) {
414
+ const found = [...models.flatMap((model) => model.status === "found" ? [[model.expected.physicalName, model.found]] : []), ...referencedModels];
415
+ return new Set(found.filter(([, model]) => hasUuidId(model)).map(([name]) => name));
416
+ }
417
+ /** A model or field name that is not a Prisma identifier can be neither matched nor printed, so it is the only problem reported. */
418
+ function invalidNameProblems(models) {
419
+ return models.flatMap((model) => [...isPslIdentifier(model.physicalName) ? [] : [{
420
+ kind: "invalid-name",
421
+ model: model.physicalName
422
+ }], ...model.fields.filter((field) => !isPslIdentifier(field.name)).map((field) => ({
423
+ kind: "invalid-name",
424
+ model: model.physicalName,
425
+ field: field.name
426
+ }))]);
427
+ }
428
+ /**
429
+ * Compares the contract with the models and fields Better Auth's table description asks for. The contract check and `auth generate` both use it.
430
+ */
431
+ function compareContract(input) {
432
+ const { contract, betterAuthOptions, namespace } = input;
433
+ const idStrategy = idStrategyOf(betterAuthOptions);
434
+ const defaultNamespace = defaultNamespaceByTarget[contract.target] ?? UNBOUND_DOMAIN_NAMESPACE_ID;
435
+ const expectedModelList = managedModels(input.tables, input);
436
+ const nameProblems = [...invalidNameProblems(expectedModelList), ...caseOnlyNameCollisions(betterAuthModels(input.tables, input)).map((models) => ({
437
+ kind: "colliding-model-names",
438
+ models
439
+ }))];
440
+ if (nameProblems.length > 0) return {
441
+ models: [],
442
+ problems: nameProblems,
443
+ referencedModels: /* @__PURE__ */ new Map(),
444
+ uuidKeyedModels: /* @__PURE__ */ new Set(),
445
+ idStrategy,
446
+ namespace,
447
+ defaultNamespace
448
+ };
449
+ const problems = [];
450
+ const models = [];
451
+ for (const expected of expectedModelList) {
452
+ const lookup = findModel(contract, expected.physicalName, namespace);
453
+ switch (lookup.kind) {
454
+ case "missing":
455
+ problems.push({
456
+ kind: "missing-model",
457
+ model: expected.physicalName
458
+ });
459
+ models.push({
460
+ status: "missing",
461
+ expected
462
+ });
463
+ break;
464
+ case "ambiguous":
465
+ problems.push({
466
+ kind: "ambiguous-model",
467
+ model: lookup.name,
468
+ namespaceIds: lookup.namespaceIds
469
+ });
470
+ models.push({
471
+ status: "ambiguous",
472
+ expected
473
+ });
474
+ break;
475
+ case "found": {
476
+ const missingFields = compareFoundModel(contract, expected, lookup, idStrategy, problems);
477
+ models.push({
478
+ status: "found",
479
+ expected,
480
+ found: lookup,
481
+ missingFields
482
+ });
483
+ break;
484
+ }
485
+ }
486
+ }
487
+ const expectedNames = new Set(expectedModelList.map((model) => model.physicalName));
488
+ const referencedModels = /* @__PURE__ */ new Map();
489
+ for (const model of expectedModelList) for (const { reference } of model.fields) {
490
+ if (reference === void 0 || expectedNames.has(reference.model)) continue;
491
+ const lookup = findModel(contract, reference.model, namespace);
492
+ if (lookup.kind === "found") referencedModels.set(reference.model, lookup);
493
+ }
494
+ return {
495
+ models,
496
+ problems,
497
+ referencedModels,
498
+ uuidKeyedModels: acceptedKindsByIdStrategy[idStrategy].includes("uuid") ? uuidKeyedModelsOf(models, referencedModels) : /* @__PURE__ */ new Set(),
499
+ idStrategy,
500
+ namespace,
501
+ defaultNamespace
502
+ };
503
+ }
504
+ //#endregion
505
+ //#region src/contract/psl-types.ts
506
+ /** How a Better Auth field is written in PSL, without `?`. A foreign key to a model whose `id` is a `Uuid` is a `Uuid`, since PostgreSQL refuses a `text` key that references a `uuid`. */
507
+ function pslTypeOf(attribute, reference, { idStrategy, uuidKeyedModels }) {
508
+ if (isIdReference(attribute)) {
509
+ if (reference !== void 0 && uuidKeyedModels.has(reference.model)) return "Uuid";
510
+ return idStrategy === "serial" ? "Int" : "String";
511
+ }
512
+ switch (attribute.type) {
513
+ case "number": return attribute.bigint === true ? "BigInt(as: number)" : "Int";
514
+ case "boolean": return "Boolean";
515
+ case "date": return "DateTime";
516
+ default: return "String";
517
+ }
518
+ }
519
+ /** The `id` field the printed PSL declares, as its columns. */
520
+ function idFieldOf(idStrategy) {
521
+ switch (idStrategy) {
522
+ case "serial": return {
523
+ name: "id",
524
+ type: "Int",
525
+ attributes: "@id @default(autoincrement())"
526
+ };
527
+ case "contract": return {
528
+ name: "id",
529
+ type: "String",
530
+ attributes: "@id @onCreate(uuid())"
531
+ };
532
+ default: return {
533
+ name: "id",
534
+ type: "String",
535
+ attributes: "@id"
536
+ };
537
+ }
538
+ }
539
+ function idLineOf(idStrategy) {
540
+ const { name, type, attributes } = idFieldOf(idStrategy);
541
+ return `${name} ${type} ${attributes}`;
542
+ }
543
+ //#endregion
544
+ //#region src/contract/print-psl.ts
545
+ const actionNames = {
546
+ cascade: "Cascade",
547
+ "no action": "NoAction",
548
+ restrict: "Restrict",
549
+ "set null": "SetNull",
550
+ "set default": "SetDefault"
551
+ };
552
+ function existingPrintedModel(found, betterAuthFields) {
553
+ return {
554
+ name: found.name,
555
+ namespaceId: found.namespaceId,
556
+ existing: true,
557
+ taken: /* @__PURE__ */ new Set([
558
+ ...betterAuthFields,
559
+ ...Object.keys(found.model.fields),
560
+ ...Object.keys(found.model.relations)
561
+ ]),
562
+ fields: [],
563
+ backRelations: [],
564
+ attributes: []
565
+ };
566
+ }
567
+ function printedModelFor(model, comparison) {
568
+ const betterAuthFields = ["id", ...model.expected.fields.map((field) => field.name)];
569
+ switch (model.status) {
570
+ case "missing": return {
571
+ name: upperFirst(model.expected.physicalName),
572
+ namespaceId: comparison.namespace ?? comparison.defaultNamespace,
573
+ existing: false,
574
+ taken: new Set(betterAuthFields),
575
+ fields: [],
576
+ backRelations: [],
577
+ attributes: []
578
+ };
579
+ case "found": return existingPrintedModel(model.found, betterAuthFields);
580
+ case "ambiguous": return;
581
+ }
582
+ }
583
+ function typeName(of, from) {
584
+ return of.namespaceId === from.namespaceId ? of.name : `${of.namespaceId}.${of.name}`;
585
+ }
586
+ function scalarLine(field, comparison) {
587
+ const optional = field.attribute.required === false ? "?" : "";
588
+ const type = `${pslTypeOf(field.attribute, field.reference, comparison)}${optional}`;
589
+ return field.attribute.unique === true ? [
590
+ field.name,
591
+ type,
592
+ "@unique"
593
+ ] : [field.name, type];
594
+ }
595
+ function idLine(comparison) {
596
+ const { name, type, attributes } = idFieldOf(comparison.idStrategy);
597
+ return [
598
+ name,
599
+ type,
600
+ attributes
601
+ ];
602
+ }
603
+ function freeName(name, printed) {
604
+ let free = name;
605
+ while (printed.taken.has(free)) free = `${free}_`;
606
+ return free;
607
+ }
608
+ function relationFieldName(foreignKey, holder) {
609
+ const stripped = foreignKey.endsWith("Id") ? foreignKey.slice(0, -2) : foreignKey;
610
+ return stripped === "" || stripped === foreignKey || holder.taken.has(stripped) ? freeName(`${foreignKey}Relation`, holder) : stripped;
611
+ }
612
+ function foreignKeyCount(expected, referenced) {
613
+ return expected.fields.filter((field) => field.reference?.model === referenced).length;
614
+ }
615
+ function indexLines(expected) {
616
+ const lines = [...expected.fields.filter((field) => field.attribute.index === true && field.attribute.unique !== true).map((field) => `@@index([${field.name}])`), ...expected.indexes.map((index) => `${index.unique ? "@@unique" : "@@index"}([${index.fields.join(", ")}])`)];
617
+ return [...new Set(lines)];
618
+ }
619
+ function alignedLines(lines) {
620
+ const nameWidth = Math.max(0, ...lines.map(([name]) => name.length));
621
+ const typeWidth = Math.max(0, ...lines.map(([, type]) => type.length));
622
+ return lines.map(([name, type, attributes]) => attributes === void 0 || attributes === "" ? `${name.padEnd(nameWidth)} ${type}` : `${name.padEnd(nameWidth)} ${type.padEnd(typeWidth)} ${attributes}`);
623
+ }
624
+ function blockText(block, indent) {
625
+ const body = [...block.fieldLines.map((line) => ` ${line}`)];
626
+ if (block.attributeLines.length > 0) body.push("", ...block.attributeLines.map((line) => ` ${line}`));
627
+ return [
628
+ `model ${block.modelName} {`,
629
+ ...body,
630
+ "}"
631
+ ].map((line) => line === "" ? "" : `${indent}${line}`).join("\n");
632
+ }
633
+ /** PSL text for printed blocks; blocks of missing models go inside a `namespace` block when the adapter's `namespace` option is set. */
634
+ function renderBlocks(blocks, namespace) {
635
+ const chunks = [];
636
+ let run = [];
637
+ const flush = () => {
638
+ if (run.length === 0) return;
639
+ const inner = run.map((block) => blockText(block, " ")).join("\n\n");
640
+ chunks.push(`namespace ${namespace} {\n${inner}\n}`);
641
+ run = [];
642
+ };
643
+ for (const block of blocks) {
644
+ if (namespace !== void 0 && !block.existing) {
645
+ run.push(block);
646
+ continue;
647
+ }
648
+ flush();
649
+ chunks.push(blockText(block, ""));
650
+ }
651
+ flush();
652
+ return chunks.join("\n\n");
653
+ }
654
+ /**
655
+ * The PSL that adds what the comparison found missing: whole models for missing models, and the missing fields and new back-relation fields of existing models.
656
+ */
657
+ function printPsl(comparison) {
658
+ const printedModels = /* @__PURE__ */ new Map();
659
+ for (const model of comparison.models) {
660
+ const printed = printedModelFor(model, comparison);
661
+ if (printed !== void 0) printedModels.set(model.expected.physicalName, printed);
662
+ }
663
+ for (const [physicalName, found] of comparison.referencedModels) printedModels.set(physicalName, existingPrintedModel(found, []));
664
+ const notes = [];
665
+ for (const model of comparison.models) {
666
+ const holder = printedModels.get(model.expected.physicalName);
667
+ if (holder === void 0) continue;
668
+ if (model.status === "found") {
669
+ for (const name of model.missingFields) {
670
+ const field = model.expected.fields.find((candidate) => candidate.name === name);
671
+ holder.fields.push(field === void 0 ? idLine(comparison) : scalarLine(field, comparison));
672
+ }
673
+ continue;
674
+ }
675
+ holder.fields.push(idLine(comparison));
676
+ for (const field of model.expected.fields) {
677
+ holder.fields.push(scalarLine(field, comparison));
678
+ const reference = field.reference;
679
+ if (reference === void 0) continue;
680
+ const referenced = printedModels.get(reference.model);
681
+ const optional = field.attribute.required === false;
682
+ let action = reference.onDelete;
683
+ if (action === "set null" && !optional || action === "set default") {
684
+ notes.push(`${holder.name}.${field.name}: Better Auth asks for onDelete ${action}, which needs ${action === "set null" ? "an optional field" : "a default"}; NoAction is printed instead`);
685
+ action = "no action";
686
+ }
687
+ const relationName = relationFieldName(field.name, holder);
688
+ holder.taken.add(relationName);
689
+ let relationLabel;
690
+ if (referenced !== void 0) {
691
+ const list = field.attribute.unique !== true;
692
+ const base = `${lowerFirst(holder.name)}${list ? "s" : ""}`;
693
+ const named = referenced.taken.has(base) || foreignKeyCount(model.expected, reference.model) > 1;
694
+ const backName = named ? freeName(`${base}By${upperFirst(field.name)}`, referenced) : base;
695
+ relationLabel = named ? `"${holder.name}_${field.name}"` : void 0;
696
+ referenced.taken.add(backName);
697
+ referenced.backRelations.push([
698
+ backName,
699
+ `${typeName(holder, referenced)}${list ? "[]" : "?"}`,
700
+ relationLabel === void 0 ? void 0 : `@relation(${relationLabel})`
701
+ ]);
702
+ }
703
+ const referencedType = referenced === void 0 ? upperFirst(reference.model) : typeName(referenced, holder);
704
+ const relationArguments = [
705
+ ...relationLabel === void 0 ? [] : [relationLabel],
706
+ `fields: [${field.name}]`,
707
+ `references: [${reference.field}]`,
708
+ `onDelete: ${actionNames[action]}`
709
+ ].join(", ");
710
+ holder.fields.push([
711
+ relationName,
712
+ `${referencedType}${optional ? "?" : ""}`,
713
+ `@relation(${relationArguments})`
714
+ ]);
715
+ }
716
+ holder.attributes.push(...indexLines(model.expected), `@@map("${model.expected.physicalName}")`);
717
+ }
718
+ const blocks = [];
719
+ for (const printed of printedModels.values()) {
720
+ const lines = [...printed.fields, ...printed.backRelations];
721
+ if (lines.length === 0) continue;
722
+ blocks.push({
723
+ modelName: printed.name,
724
+ existing: printed.existing,
725
+ fieldLines: alignedLines(lines),
726
+ attributeLines: printed.attributes
727
+ });
728
+ }
729
+ return {
730
+ blocks,
731
+ notes,
732
+ text: renderBlocks(blocks, comparison.namespace)
733
+ };
734
+ }
735
+ //#endregion
736
+ //#region src/contract/message.ts
737
+ function section(title, lines) {
738
+ return lines.length === 0 ? [] : [
739
+ `${title}:`,
740
+ "",
741
+ ...lines.map((line) => ` ${line}`),
742
+ ""
743
+ ];
744
+ }
745
+ function changeLines(comparison) {
746
+ const lines = [];
747
+ const idLinesPrinted = /* @__PURE__ */ new Set();
748
+ for (const problem of comparison.problems) switch (problem.kind) {
749
+ case "ambiguous-model":
750
+ lines.push(ambiguousModelMessage(problem.model, problem.namespaceIds));
751
+ break;
752
+ case "optional-field-not-nullable":
753
+ lines.push(`${problem.model}.${problem.field}: must be \`${pslTypeOf(problem.attribute, problem.reference, comparison)}?\`, because Better Auth can write null to it`);
754
+ break;
755
+ case "id-without-default":
756
+ case "wrong-type":
757
+ if (problem.kind === "id-without-default" || problem.attribute === void 0) {
758
+ if (idLinesPrinted.has(problem.model)) break;
759
+ idLinesPrinted.add(problem.model);
760
+ lines.push(`${problem.model}.id: must be \`${idLineOf(comparison.idStrategy)}\``);
761
+ break;
762
+ }
763
+ lines.push(`${problem.model}.${problem.field}: must be \`${pslTypeOf(problem.attribute, problem.reference, comparison)}${mayBeNull(problem.attribute) ? "?" : ""}\` (found ${problem.found})`);
764
+ break;
765
+ }
766
+ return lines;
767
+ }
768
+ function unwrittenLines(comparison) {
769
+ return comparison.problems.flatMap((problem) => problem.kind === "required-field-not-written" ? [`${problem.model}.${problem.field}: make it optional or give it a default`] : []);
770
+ }
771
+ /**
772
+ * The message the contract check and `auth generate` report, or `undefined` when the contract holds everything Better Auth needs.
773
+ */
774
+ function contractMessage(comparison) {
775
+ if (comparison.problems.length === 0) return void 0;
776
+ const invalidNames = comparison.problems.flatMap((problem) => {
777
+ if (problem.kind === "colliding-model-names") return [caseOnlyNameCollisionMessage(problem.models)];
778
+ if (problem.kind !== "invalid-name") return [];
779
+ const message = problem.field === void 0 ? invalidModelNameMessage(problem.model) : invalidFieldNameMessage(problem.model, problem.field);
780
+ return message === void 0 ? [] : [message];
781
+ });
782
+ if (invalidNames.length > 0) return invalidNames.join("\n");
783
+ const psl = printPsl(comparison);
784
+ const additions = psl.text === "" ? [] : [
785
+ "Add to your contract:",
786
+ "",
787
+ psl.text,
788
+ ""
789
+ ];
790
+ return [
791
+ additions.length > 0 ? "Your Prisma contract is missing models or fields that Better Auth needs." : "Your Prisma contract does not match what Better Auth needs.",
792
+ "",
793
+ ...additions,
794
+ ...section("Change in your contract", changeLines(comparison)),
795
+ ...section("Fields Better Auth does not write", unwrittenLines(comparison)),
796
+ ...section("Notes", psl.notes),
797
+ "Then run `prisma contract emit` and update your database."
798
+ ].join("\n");
799
+ }
800
+ //#endregion
801
+ //#region src/contract/contract-check.ts
802
+ /** The error the contract check rejects with and `createSchema` throws. Its `code` is what Better Auth's CLI looks for. */
803
+ function contractMismatchError(message) {
804
+ return Object.assign(new BetterAuthError(message), { code: "SCHEMA_MISMATCH" });
805
+ }
806
+ /** The mismatch error for a contract, or `undefined` when it holds everything Better Auth needs. */
807
+ function contractMismatch(input) {
808
+ const message = contractMessage(compareContract(input));
809
+ return message === void 0 ? void 0 : contractMismatchError(message);
810
+ }
811
+ /**
812
+ * A check that compares the contract on its first call and keeps the result: `undefined` when the contract is complete, and a promise rejected with the same error on every call when it is not.
813
+ */
814
+ function createContractCheck(input) {
815
+ let verdict;
816
+ return () => {
817
+ if (verdict === void 0) try {
818
+ const error = contractMismatch(input());
819
+ verdict = error === void 0 ? { clean: true } : {
820
+ clean: false,
821
+ error
822
+ };
823
+ } catch (error) {
824
+ verdict = {
825
+ clean: false,
826
+ error
827
+ };
828
+ }
829
+ return verdict.clean ? void 0 : Promise.reject(verdict.error);
830
+ };
831
+ }
832
+ /**
833
+ * Registers the check with Better Auth, which runs it before requests, server-side API calls and transactions, and for `auth check`. Better Auth labels the entrypoint internal, so a version without `registerSchemaCheck` runs the adapter without a check.
834
+ */
835
+ function registerContractCheck(adapter, check, betterAuthOptions) {
836
+ if (typeof internal.registerSchemaCheck !== "function") return;
837
+ internal.registerSchemaCheck(adapter, check, { runtimeEnabled: betterAuthOptions.advanced?.database?.validateSchema !== false });
838
+ }
839
+ //#endregion
840
+ //#region src/filters.ts
841
+ /** The codec id a raw expression over the field returns. A field that is not a single scalar, or whose codec is known not to hold text, supports no pattern or case-insensitive comparison; a codec the table does not know is tried. */
842
+ function scalarCodecIdOf(model, field, operator) {
843
+ const type = model.model.fields[field];
844
+ if (type?.type.kind !== "scalar" || type.many) throw unsupportedError(model, field, operator);
845
+ const kind = codecKind(type.type.codecId);
846
+ if (kind !== void 0 && kind !== "string") throw unsupportedError(model, field, operator);
847
+ return type.type.codecId;
848
+ }
849
+ function fieldTypeOf(model, field) {
850
+ const contractField = model.model.fields[field];
851
+ return contractField === void 0 ? "unknown type" : describeFieldType(contractField);
852
+ }
853
+ function unsupportedError(model, field, operator) {
854
+ return new BetterAuthError(`Field "${model.name}.${field}" (${fieldTypeOf(model, field)}) does not support ${operator}.`);
855
+ }
856
+ /** A field of the callback's model accessor; an unknown field raises the ORM client's own error. */
857
+ function fieldOf(accessor, field) {
858
+ return property(accessor, field);
859
+ }
860
+ function call(field, method, model, name, operator, ...args) {
861
+ if (!hasMethod(field, method)) throw unsupportedError(model, name, operator);
862
+ return asCondition(callMethod(field, method, ...args));
863
+ }
864
+ function presentValues(value) {
865
+ return (Array.isArray(value) ? [...value] : [value]).filter((item) => item !== null && item !== void 0);
866
+ }
867
+ function allStrings(values) {
868
+ return values.length > 0 && values.every((item) => typeof item === "string");
869
+ }
870
+ function sensitivePattern({ fns, field, codecId }, operator, value) {
871
+ const expected = fns.raw`${value}`.returns(codecId);
872
+ switch (operator) {
873
+ case "starts_with": return asCondition(fns.eq(fns.raw`substr(${field}, 1, length(${value}))`.returns(codecId), expected));
874
+ case "ends_with": return asCondition(fns.eq(fns.raw`substr(${field}, length(${field}) - length(${value}) + 1)`.returns(codecId), expected));
875
+ default: return asCondition(fns.ne(fns.raw`replace(${field}, ${value}, '')`.returns(codecId), fns.raw`${field}`.returns(codecId)));
876
+ }
877
+ }
878
+ function insensitivePattern({ fns, field, codecId }, operator, value) {
879
+ const expected = fns.raw`lower(${value})`.returns(codecId);
880
+ switch (operator) {
881
+ case "eq": return asCondition(fns.eq(fns.raw`lower(${field})`.returns(codecId), expected));
882
+ case "ne": return asCondition(fns.ne(fns.raw`lower(${field})`.returns(codecId), expected));
883
+ case "starts_with": return asCondition(fns.eq(fns.raw`substr(lower(${field}), 1, length(lower(${value})))`.returns(codecId), expected));
884
+ case "ends_with": return asCondition(fns.eq(fns.raw`substr(lower(${field}), length(lower(${field})) - length(lower(${value})) + 1)`.returns(codecId), expected));
885
+ default: return asCondition(fns.ne(fns.raw`replace(lower(${field}), lower(${value}), '')`.returns(codecId), fns.raw`lower(${field})`.returns(codecId)));
886
+ }
887
+ }
888
+ function clauseCondition(accessor, { fns }, model, clause) {
889
+ const name = clause.field;
890
+ const field = fieldOf(accessor, name);
891
+ const operator = clause.operator ?? "eq";
892
+ const value = clause.value;
893
+ const insensitive = clause.mode === "insensitive";
894
+ const pattern = () => ({
895
+ fns,
896
+ field,
897
+ codecId: scalarCodecIdOf(model, name, operator)
898
+ });
899
+ const method = (methodName, ...args) => call(field, methodName, model, name, operator, ...args);
900
+ switch (operator) {
901
+ case "eq":
902
+ case "ne":
903
+ if (value === null) return method(operator === "eq" ? "isNull" : "isNotNull");
904
+ if (insensitive && typeof value === "string") return insensitivePattern(pattern(), operator, value);
905
+ return method(operator === "eq" ? "eq" : "neq", value);
906
+ case "lt":
907
+ case "lte":
908
+ case "gt":
909
+ case "gte": return method(operator, value);
910
+ case "in":
911
+ case "not_in": {
912
+ const values = presentValues(value);
913
+ const isIn = operator === "in";
914
+ if (values.length === 0) return isIn ? or() : and();
915
+ if (insensitive && allStrings(values)) {
916
+ const each = values.map((item) => insensitivePattern(pattern(), isIn ? "eq" : "ne", item));
917
+ return isIn ? or(...each) : and(...each);
918
+ }
919
+ return method(isIn ? "in" : "notIn", values);
920
+ }
921
+ case "starts_with":
922
+ case "ends_with":
923
+ case "contains": {
924
+ const context = pattern();
925
+ const text = String(value);
926
+ if (text === "") return method("isNotNull");
927
+ return insensitive ? insensitivePattern(context, operator, text) : sensitivePattern(context, operator, text);
928
+ }
929
+ default: throw new BetterAuthError(`Better Auth filter operator "${String(operator)}" is not supported.`);
930
+ }
931
+ }
932
+ /** The `where` callback for Better Auth's flat list of clauses: AND clauses, then one OR group. */
933
+ function whereFilter(model, where) {
934
+ return (accessor, tools) => {
935
+ if (where === void 0 || where.length === 0) return all();
936
+ const conditionOf = (clause) => clauseCondition(accessor, tools, model, clause);
937
+ const andClauses = where.filter((clause) => clause.connector !== "OR").map(conditionOf);
938
+ const orClauses = where.filter((clause) => clause.connector === "OR").map(conditionOf);
939
+ if (orClauses.length === 0) return and(...andClauses);
940
+ if (andClauses.length === 0) return or(...orClauses);
941
+ return and(...andClauses, or(...orClauses));
942
+ };
943
+ }
944
+ //#endregion
945
+ //#region src/joins.ts
946
+ function sameFields(fields, column) {
947
+ return fields.length === 1 && fields[0] === column;
948
+ }
949
+ function matchingRelation(base, joined, on) {
950
+ return Object.entries(base.model.relations).find(([, relation]) => relation.to.model === joined.name && relation.to.namespace === joined.namespaceId && "on" in relation && sameFields(relation.on.localFields, on.from) && sameFields(relation.on.targetFields, on.to));
951
+ }
952
+ /**
953
+ * Adds an `include` for each joined model the base model declares a matching relation to. A join with no matching relation is left out, and Better Auth fetches its rows itself.
954
+ */
955
+ function planJoins(collection, base, join, collections, debugLog) {
956
+ const included = [];
957
+ let planned = collection;
958
+ for (const [key, config] of Object.entries(join ?? {})) {
959
+ const match = matchingRelation(base, collections.model(key), config.on);
960
+ if (match === void 0) {
961
+ debugLog(`Join of "${key}" on "${base.name}" runs as separate queries: the contract declares no relation from ${base.name}.${config.on.from} to ${key}.${config.on.to}. Declare the relation to join in one query.`);
962
+ continue;
963
+ }
964
+ const [relation, { cardinality }] = match;
965
+ const limit = config.limit;
966
+ planned = (cardinality === "1:N" || cardinality === "N:M") && limit !== void 0 ? planned.include(relation, (related) => related.limit(limit)) : planned.include(relation);
967
+ included.push({
968
+ relation,
969
+ key
970
+ });
971
+ }
972
+ return {
973
+ collection: planned,
974
+ included
975
+ };
976
+ }
977
+ function moveJoinedRows(row, included) {
978
+ if (included.length === 0) return row;
979
+ const moved = { ...row };
980
+ for (const { relation } of included) delete moved[relation];
981
+ for (const { relation, key } of included) moved[key] = row[relation];
982
+ return moved;
983
+ }
984
+ //#endregion
985
+ //#region src/adapter.ts
986
+ const supportedTargets = ["postgres", "sqlite"];
987
+ function assertClient(db, adapterOptions) {
988
+ const contract = db.contract;
989
+ if (contract === void 0) throw new BetterAuthError("prismaAdapter needs the Prisma client, not a transaction.");
990
+ if (!supportedTargets.includes(contract.target)) throw new BetterAuthError(`@prisma/orm-better-auth supports Postgres and SQLite. This client's database is "${contract.target}".`);
991
+ const namespace = adapterOptions.namespace;
992
+ if (namespace !== void 0 && !Object.hasOwn(contract.domain.namespaces, namespace)) throw new BetterAuthError(`Namespace "${namespace}" is not in your Prisma contract.`);
993
+ }
994
+ /** For each physical model name, the fields a read without `select` returns: `id` and every field of Better Auth's table description. */
995
+ function defaultSelections(schema, betterAuthOptions, usePlural) {
996
+ return new Map(betterAuthModels(schema, {
997
+ betterAuthOptions,
998
+ usePlural
999
+ }).map((model) => [model.physicalName, ["id", ...model.fields.map((field) => field.name)]]));
1000
+ }
1001
+ function rowCount(result) {
1002
+ const count = result["n"];
1003
+ if (typeof count !== "number") throw new BetterAuthError("The count query returned no number.");
1004
+ return count;
1005
+ }
1006
+ function asCustomAdapter(adapter) {
1007
+ return blindCast(adapter);
1008
+ }
1009
+ /** The calls Better Auth's factory makes, over one ORM client root: the client's or a transaction's. */
1010
+ function customAdapter({ orm, contract, instance, adapterOptions }) {
1011
+ const usePlural = adapterOptions.usePlural ?? false;
1012
+ const { collections } = instance;
1013
+ return ({ schema, options: betterAuthOptions, getFieldName, debugLog }) => {
1014
+ const resolve = (model) => {
1015
+ if (instance.nameCollision === void 0) {
1016
+ const [collision] = caseOnlyNameCollisions(betterAuthModels(schema, {
1017
+ betterAuthOptions,
1018
+ usePlural
1019
+ }));
1020
+ instance.nameCollision = collision === void 0 ? null : contractMismatchError(caseOnlyNameCollisionMessage(collision));
1021
+ }
1022
+ if (instance.nameCollision !== null) throw instance.nameCollision;
1023
+ const found = collections.model(model);
1024
+ return {
1025
+ found,
1026
+ collection: collections.collection(orm, found)
1027
+ };
1028
+ };
1029
+ const assertFieldNames = (model, fields) => {
1030
+ for (const field of fields) assertFieldName(model, field);
1031
+ };
1032
+ const filterFor = (model, found, where) => {
1033
+ assertFieldNames(model, (where ?? []).map((clause) => clause.field));
1034
+ return whereFilter(found, where);
1035
+ };
1036
+ const selectionOf = (model) => {
1037
+ instance.defaultSelections ??= defaultSelections(schema, betterAuthOptions, usePlural);
1038
+ const fields = instance.defaultSelections.get(model);
1039
+ if (fields === void 0) throw new BetterAuthError(`Better Auth's table description has no model "${model}".`);
1040
+ return fields;
1041
+ };
1042
+ const selected = ({ model, modelKey = model }, select) => {
1043
+ const fields = select !== void 0 && select.length > 0 ? select.map((field) => getFieldName({
1044
+ model: modelKey,
1045
+ field
1046
+ })) : selectionOf(model);
1047
+ assertFieldNames(model, fields);
1048
+ return fields;
1049
+ };
1050
+ return asCustomAdapter({
1051
+ async create({ model, data }) {
1052
+ assertFieldNames(model, Object.keys(data));
1053
+ const { collection } = resolve(model);
1054
+ return collection.create(data);
1055
+ },
1056
+ async findOne({ model, modelKey, where, select, join }) {
1057
+ const { found, collection } = resolve(model);
1058
+ const joins = planJoins(collection.where(filterFor(model, found, where)).select(...selected({
1059
+ model,
1060
+ modelKey
1061
+ }, select)), found, join, collections, debugLog);
1062
+ const row = await joins.collection.first();
1063
+ return row === null ? null : moveJoinedRows(row, joins.included);
1064
+ },
1065
+ async findMany({ model, modelKey, where, limit, select, sortBy, offset, join }) {
1066
+ const { found, collection } = resolve(model);
1067
+ let query = collection.where(filterFor(model, found, where)).select(...selected({
1068
+ model,
1069
+ modelKey
1070
+ }, select));
1071
+ if (sortBy !== void 0) {
1072
+ const field = getFieldName({
1073
+ model: modelKey ?? model,
1074
+ field: sortBy.field
1075
+ });
1076
+ assertFieldNames(model, [field]);
1077
+ const direction = sortBy.direction;
1078
+ if (direction !== "asc" && direction !== "desc") throw new BetterAuthError(`Sort direction "${String(direction)}" is not supported.`);
1079
+ query = query.orderBy((accessor) => {
1080
+ const sorted = fieldOf(accessor, field);
1081
+ if (!hasMethod(sorted, direction)) throw unsupportedError(found, field, "sorting");
1082
+ return callMethod(sorted, direction);
1083
+ });
1084
+ }
1085
+ query = query.limit(limit);
1086
+ if (offset !== void 0) query = query.offset(offset);
1087
+ const joins = planJoins(query, found, join, collections, debugLog);
1088
+ return (await joins.collection.all()).map((row) => moveJoinedRows(row, joins.included));
1089
+ },
1090
+ async count({ model, where }) {
1091
+ const { found, collection } = resolve(model);
1092
+ return rowCount(await collection.where(filterFor(model, found, where)).aggregate((aggregates) => ({ n: aggregates.count() })));
1093
+ },
1094
+ async update({ model, where, update }) {
1095
+ assertFieldNames(model, Object.keys(update));
1096
+ const { found, collection } = resolve(model);
1097
+ return collection.where(filterFor(model, found, where)).update(update);
1098
+ },
1099
+ async updateMany({ model, where, update }) {
1100
+ assertFieldNames(model, Object.keys(update));
1101
+ const { found, collection } = resolve(model);
1102
+ return collection.where(filterFor(model, found, where)).updateAndCount(update);
1103
+ },
1104
+ async delete({ model, where }) {
1105
+ const { found, collection } = resolve(model);
1106
+ await collection.where(filterFor(model, found, where)).deleteAndCount();
1107
+ },
1108
+ async deleteMany({ model, where }) {
1109
+ const { found, collection } = resolve(model);
1110
+ return collection.where(filterFor(model, found, where)).deleteAndCount();
1111
+ },
1112
+ async createSchema({ file, tables }) {
1113
+ const error = contractMismatch({
1114
+ contract,
1115
+ tables,
1116
+ betterAuthOptions,
1117
+ namespace: adapterOptions.namespace,
1118
+ usePlural
1119
+ });
1120
+ if (error !== void 0) throw error;
1121
+ return {
1122
+ code: "",
1123
+ path: file ?? "prisma/contract.prisma"
1124
+ };
1125
+ }
1126
+ });
1127
+ };
1128
+ }
1129
+ function factoryConfig(adapterOptions, transaction) {
1130
+ return {
1131
+ adapterId: "prisma-8",
1132
+ adapterName: "Prisma 8",
1133
+ usePlural: adapterOptions.usePlural ?? false,
1134
+ debugLogs: adapterOptions.debugLogs ?? false,
1135
+ supportsDates: true,
1136
+ supportsBooleans: true,
1137
+ supportsNumericIds: true,
1138
+ supportsJSON: false,
1139
+ supportsArrays: false,
1140
+ supportsUUIDs: false,
1141
+ transaction
1142
+ };
1143
+ }
1144
+ /**
1145
+ * A Better Auth database adapter over a Prisma 8 Postgres or SQLite client.
1146
+ *
1147
+ * @example
1148
+ * ```ts
1149
+ * export const auth = betterAuth({ database: prismaAdapter(db) });
1150
+ * ```
1151
+ */
1152
+ function prismaAdapter(db, adapterOptions = {}) {
1153
+ assertClient(db, adapterOptions);
1154
+ return (betterAuthOptions) => {
1155
+ const context = {
1156
+ orm: db.orm,
1157
+ contract: db.contract,
1158
+ instance: {
1159
+ collections: createModelCollections(db.contract, adapterOptions.namespace),
1160
+ defaultSelections: void 0,
1161
+ nameCollision: void 0
1162
+ },
1163
+ adapterOptions
1164
+ };
1165
+ const adapter = createAdapterFactory({
1166
+ config: factoryConfig(adapterOptions, adapterOptions.transaction === true ? (callback) => db.transaction((tx) => callback(createAdapterFactory({
1167
+ config: factoryConfig(adapterOptions, false),
1168
+ adapter: customAdapter({
1169
+ ...context,
1170
+ orm: tx.orm
1171
+ })
1172
+ })(betterAuthOptions))) : false),
1173
+ adapter: customAdapter(context)
1174
+ })(betterAuthOptions);
1175
+ registerContractCheck(adapter, createContractCheck(() => ({
1176
+ contract: db.contract,
1177
+ tables: getAuthTables(betterAuthOptions),
1178
+ betterAuthOptions,
1179
+ namespace: adapterOptions.namespace,
1180
+ usePlural: adapterOptions.usePlural ?? false
1181
+ })), betterAuthOptions);
1182
+ return adapter;
1183
+ };
1184
+ }
1185
+ //#endregion
1186
+ export { prismaAdapter };
1187
+
1188
+ //# sourceMappingURL=index.mjs.map