@prisma/orm-better-auth 8.0.0-rc.25-dev.7 → 8.0.0-rc.25-dev.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -19
- package/dist/contract-check-Cw4rCQvX.mjs +799 -0
- package/dist/contract-check-Cw4rCQvX.mjs.map +1 -0
- package/dist/edited-contract-source-uFJmCt41.mjs +487 -0
- package/dist/edited-contract-source-uFJmCt41.mjs.map +1 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +5 -774
- package/dist/index.mjs.map +1 -1
- package/package.json +13 -10
|
@@ -0,0 +1,799 @@
|
|
|
1
|
+
import { BetterAuthError } from "@better-auth/core/error";
|
|
2
|
+
import { UNBOUND_DOMAIN_NAMESPACE_ID } from "@prisma/orm-framework/contract/default-namespace";
|
|
3
|
+
import { resolveStorageTable } from "@prisma/orm-family-sql/contract/resolve-storage-table";
|
|
4
|
+
import * as internal from "@better-auth/core/db/internal";
|
|
5
|
+
//#region src/models/identifiers.ts
|
|
6
|
+
const pslIdentifier = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
7
|
+
function isPslIdentifier(name) {
|
|
8
|
+
return pslIdentifier.test(name);
|
|
9
|
+
}
|
|
10
|
+
/** The message for a Better Auth model name that is not a Prisma identifier, or `undefined` when it is one. */
|
|
11
|
+
function invalidModelNameMessage(name) {
|
|
12
|
+
if (isPslIdentifier(name)) return void 0;
|
|
13
|
+
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.`;
|
|
14
|
+
}
|
|
15
|
+
/** The message for a Better Auth field name that is not a Prisma identifier, or `undefined` when it is one. */
|
|
16
|
+
function invalidFieldNameMessage(model, field) {
|
|
17
|
+
if (isPslIdentifier(field)) return void 0;
|
|
18
|
+
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.`;
|
|
19
|
+
}
|
|
20
|
+
/** The message for Better Auth models whose names differ only in the case of the first letter. */
|
|
21
|
+
function caseOnlyNameCollisionMessage(names) {
|
|
22
|
+
const quoted = names.map((name) => `"${name}"`);
|
|
23
|
+
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.`;
|
|
24
|
+
}
|
|
25
|
+
function assertModelName(name) {
|
|
26
|
+
const message = invalidModelNameMessage(name);
|
|
27
|
+
if (message !== void 0) throw new BetterAuthError(message);
|
|
28
|
+
}
|
|
29
|
+
function assertFieldName(model, field) {
|
|
30
|
+
const message = invalidFieldNameMessage(model, field);
|
|
31
|
+
if (message !== void 0) throw new BetterAuthError(message);
|
|
32
|
+
}
|
|
33
|
+
function upperFirst(name) {
|
|
34
|
+
return name.charAt(0).toUpperCase() + name.slice(1);
|
|
35
|
+
}
|
|
36
|
+
function lowerFirst(name) {
|
|
37
|
+
return name.charAt(0).toLowerCase() + name.slice(1);
|
|
38
|
+
}
|
|
39
|
+
//#endregion
|
|
40
|
+
//#region src/models/model-lookup.ts
|
|
41
|
+
function missingModelMessage(physicalName) {
|
|
42
|
+
return `Model "${physicalName}" is not in your Prisma contract. Run \`npx auth@latest generate\` to see what to add.`;
|
|
43
|
+
}
|
|
44
|
+
function ambiguousModelMessage(name, namespaceIds) {
|
|
45
|
+
return `Model "${name}" is in more than one namespace of your Prisma contract (${namespaceIds.join(", ")}). Set the adapter's "namespace" option.`;
|
|
46
|
+
}
|
|
47
|
+
/** The contract model names a Better Auth physical model name is looked up by, in order: the exact name, then the name with its first letter upper-cased. */
|
|
48
|
+
function modelNameCandidates(physicalName) {
|
|
49
|
+
return [.../* @__PURE__ */ new Set([physicalName, upperFirst(physicalName)])];
|
|
50
|
+
}
|
|
51
|
+
/** Whether the adapter looks for Better Auth's models in a namespace: every namespace without the adapter's `namespace` option, else only the one it names. */
|
|
52
|
+
function isSearchedNamespace(namespaceId, namespace) {
|
|
53
|
+
return namespace === void 0 || namespaceId === namespace;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* 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.
|
|
57
|
+
*/
|
|
58
|
+
function findModel(contract, physicalName, namespace) {
|
|
59
|
+
const namespaces = contract.domain.namespaces;
|
|
60
|
+
const searched = Object.keys(namespaces).filter((id) => isSearchedNamespace(id, namespace));
|
|
61
|
+
for (const name of modelNameCandidates(physicalName)) {
|
|
62
|
+
const hits = searched.filter((id) => Object.hasOwn(namespaces[id]?.models ?? {}, name)).sort();
|
|
63
|
+
const [only] = hits;
|
|
64
|
+
if (hits.length > 1) return {
|
|
65
|
+
kind: "ambiguous",
|
|
66
|
+
name,
|
|
67
|
+
namespaceIds: hits
|
|
68
|
+
};
|
|
69
|
+
const model = only === void 0 ? void 0 : namespaces[only]?.models[name];
|
|
70
|
+
if (only !== void 0 && model !== void 0) return {
|
|
71
|
+
kind: "found",
|
|
72
|
+
name,
|
|
73
|
+
namespaceId: only,
|
|
74
|
+
model
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
return { kind: "missing" };
|
|
78
|
+
}
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region src/models/better-auth-models.ts
|
|
81
|
+
function physicalName(modelName, usePlural) {
|
|
82
|
+
return usePlural ? `${modelName}s` : modelName;
|
|
83
|
+
}
|
|
84
|
+
function isOmitted(key, table, options) {
|
|
85
|
+
if (table.disableMigrations === true) return true;
|
|
86
|
+
return key === "session" && options.secondaryStorage !== void 0 && options.session?.storeSessionInDatabase !== true;
|
|
87
|
+
}
|
|
88
|
+
function referencedTable(tables, model) {
|
|
89
|
+
return tables[model] ?? Object.values(tables).find((table) => table.modelName === model);
|
|
90
|
+
}
|
|
91
|
+
function resolveReference(tables, references, usePlural) {
|
|
92
|
+
const table = referencedTable(tables, references.model);
|
|
93
|
+
const field = table?.fields[references.field];
|
|
94
|
+
return {
|
|
95
|
+
model: physicalName(table?.modelName ?? references.model, usePlural),
|
|
96
|
+
field: field?.fieldName || references.field,
|
|
97
|
+
onDelete: references.onDelete ?? "cascade"
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* 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.
|
|
102
|
+
*/
|
|
103
|
+
function betterAuthModels(tables, { betterAuthOptions, usePlural }) {
|
|
104
|
+
const merged = /* @__PURE__ */ new Map();
|
|
105
|
+
for (const [key, table] of Object.entries(tables)) {
|
|
106
|
+
const name = physicalName(table.modelName, usePlural);
|
|
107
|
+
const model = merged.get(name) ?? {
|
|
108
|
+
fields: /* @__PURE__ */ new Map(),
|
|
109
|
+
indexes: [],
|
|
110
|
+
managed: false
|
|
111
|
+
};
|
|
112
|
+
model.managed ||= !isOmitted(key, table, betterAuthOptions);
|
|
113
|
+
merged.set(name, model);
|
|
114
|
+
for (const [fieldKey, attribute] of Object.entries(table.fields)) {
|
|
115
|
+
const fieldName = attribute.fieldName || fieldKey;
|
|
116
|
+
if (fieldName === "id") continue;
|
|
117
|
+
model.fields.set(fieldName, {
|
|
118
|
+
name: fieldName,
|
|
119
|
+
attribute,
|
|
120
|
+
reference: attribute.references === void 0 ? void 0 : resolveReference(tables, attribute.references, usePlural)
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
for (const index of table.indexes ?? []) model.indexes.push({
|
|
124
|
+
fields: index.fields.map((field) => table.fields[field]?.fieldName || field),
|
|
125
|
+
unique: index.unique === true
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
return [...merged].map(([name, { fields, indexes, managed }]) => ({
|
|
129
|
+
physicalName: name,
|
|
130
|
+
fields: [...fields.values()],
|
|
131
|
+
indexes,
|
|
132
|
+
managed
|
|
133
|
+
}));
|
|
134
|
+
}
|
|
135
|
+
/** Groups of physical model names that differ only in the case of the first letter, which the adapter refuses. */
|
|
136
|
+
function caseOnlyNameCollisions(models) {
|
|
137
|
+
const byModelName = /* @__PURE__ */ new Map();
|
|
138
|
+
for (const { physicalName } of models) {
|
|
139
|
+
const name = upperFirst(physicalName);
|
|
140
|
+
byModelName.set(name, [...byModelName.get(name) ?? [], physicalName]);
|
|
141
|
+
}
|
|
142
|
+
return [...byModelName.values()].filter((names) => names.length > 1);
|
|
143
|
+
}
|
|
144
|
+
/** The models of the schema Better Auth manages, which the comparison checks. */
|
|
145
|
+
function managedModels(tables, options) {
|
|
146
|
+
return betterAuthModels(tables, options).filter((model) => model.managed);
|
|
147
|
+
}
|
|
148
|
+
function idStrategyOf(options) {
|
|
149
|
+
const generateId = options.advanced?.database?.generateId;
|
|
150
|
+
if (generateId === "serial") return "serial";
|
|
151
|
+
if (generateId === "uuid") return "uuid";
|
|
152
|
+
if (generateId === false) return "contract";
|
|
153
|
+
return "string";
|
|
154
|
+
}
|
|
155
|
+
/** 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. */
|
|
156
|
+
function mayBeNull(attribute) {
|
|
157
|
+
return attribute.required === false;
|
|
158
|
+
}
|
|
159
|
+
function isIdReference(attribute) {
|
|
160
|
+
return attribute.references?.field === "id";
|
|
161
|
+
}
|
|
162
|
+
//#endregion
|
|
163
|
+
//#region src/models/codec-kinds.ts
|
|
164
|
+
const codecKinds = [
|
|
165
|
+
"string",
|
|
166
|
+
"enum",
|
|
167
|
+
"uuid",
|
|
168
|
+
"date",
|
|
169
|
+
"number",
|
|
170
|
+
"boolean",
|
|
171
|
+
"other"
|
|
172
|
+
];
|
|
173
|
+
const codecIdsByKind = {
|
|
174
|
+
string: [
|
|
175
|
+
"pg/text@1",
|
|
176
|
+
"sql/varchar@1",
|
|
177
|
+
"sql/char@1",
|
|
178
|
+
"sqlite/text@1"
|
|
179
|
+
],
|
|
180
|
+
enum: ["pg/enum@1"],
|
|
181
|
+
uuid: ["pg/uuid@1"],
|
|
182
|
+
date: [
|
|
183
|
+
"pg/timestamptz-date@1",
|
|
184
|
+
"pg/timestamp-date@1",
|
|
185
|
+
"sqlite/datetime@1"
|
|
186
|
+
],
|
|
187
|
+
number: [
|
|
188
|
+
"pg/int2@1",
|
|
189
|
+
"pg/int4@1",
|
|
190
|
+
"pg/int8number@1",
|
|
191
|
+
"pg/float4@1",
|
|
192
|
+
"pg/float8@1",
|
|
193
|
+
"sqlite/integer@1",
|
|
194
|
+
"sqlite/real@1"
|
|
195
|
+
],
|
|
196
|
+
boolean: ["pg/bool@1", "sqlite/boolean@1"],
|
|
197
|
+
other: [
|
|
198
|
+
"pg/int8@1",
|
|
199
|
+
"pg/unboundedint@1",
|
|
200
|
+
"pg/numeric@1",
|
|
201
|
+
"pg/timestamptz-temporal@1",
|
|
202
|
+
"pg/timestamptz-string@1",
|
|
203
|
+
"pg/timestamp-temporal@1",
|
|
204
|
+
"pg/timestamp-string@1",
|
|
205
|
+
"pg/timestamp-instant@1",
|
|
206
|
+
"pg/date-temporal@1",
|
|
207
|
+
"pg/date-string@1",
|
|
208
|
+
"pg/time-temporal@1",
|
|
209
|
+
"pg/time-string@1",
|
|
210
|
+
"pg/timetz@1",
|
|
211
|
+
"pg/inet@1",
|
|
212
|
+
"pg/interval@1",
|
|
213
|
+
"pg/interval-string@1",
|
|
214
|
+
"pg/bit@1",
|
|
215
|
+
"pg/varbit@1",
|
|
216
|
+
"pg/xml@1",
|
|
217
|
+
"pg/oid@1",
|
|
218
|
+
"pg/money@1",
|
|
219
|
+
"pg/json@1",
|
|
220
|
+
"pg/jsonb@1",
|
|
221
|
+
"pg/bytea@1",
|
|
222
|
+
"sqlite/bigint@1",
|
|
223
|
+
"sqlite/decimal@1",
|
|
224
|
+
"sqlite/datetime-temporal@1",
|
|
225
|
+
"sqlite/datetime-string@1",
|
|
226
|
+
"sqlite/date-string@1",
|
|
227
|
+
"sqlite/date-temporal@1",
|
|
228
|
+
"sqlite/time-string@1",
|
|
229
|
+
"sqlite/time-temporal@1",
|
|
230
|
+
"sqlite/duration-string@1",
|
|
231
|
+
"sqlite/json@1",
|
|
232
|
+
"sqlite/blob@1"
|
|
233
|
+
]
|
|
234
|
+
};
|
|
235
|
+
const kindByCodecId = new Map(codecKinds.flatMap((kind) => codecIdsByKind[kind].map((id) => [id, kind])));
|
|
236
|
+
/** The kind of JavaScript value a codec reads and writes, or `undefined` for a codec this table does not know. */
|
|
237
|
+
function codecKind(codecId) {
|
|
238
|
+
return kindByCodecId.get(codecId);
|
|
239
|
+
}
|
|
240
|
+
//#endregion
|
|
241
|
+
//#region src/models/field-type.ts
|
|
242
|
+
/** What a contract field holds, as messages name it: its codec id, `<codec id> list`, `a value object` or `a union`. */
|
|
243
|
+
function describeFieldType(field) {
|
|
244
|
+
if (field.type.kind === "valueObject") return "a value object";
|
|
245
|
+
if (field.type.kind === "union") return "a union";
|
|
246
|
+
return field.many ? `${field.type.codecId} list` : field.type.codecId;
|
|
247
|
+
}
|
|
248
|
+
//#endregion
|
|
249
|
+
//#region src/contract/compare.ts
|
|
250
|
+
const acceptedKindsByIdStrategy = {
|
|
251
|
+
serial: ["number"],
|
|
252
|
+
uuid: ["string", "uuid"],
|
|
253
|
+
string: ["string"],
|
|
254
|
+
contract: ["string"]
|
|
255
|
+
};
|
|
256
|
+
const storageNamesIgnoreCaseByTarget = { sqlite: true };
|
|
257
|
+
const defaultNamespaceByTarget = { postgres: "public" };
|
|
258
|
+
function acceptedKinds(attribute, idStrategy) {
|
|
259
|
+
if (isIdReference(attribute)) return acceptedKindsByIdStrategy[idStrategy];
|
|
260
|
+
switch (attribute.type) {
|
|
261
|
+
case "number": return ["number"];
|
|
262
|
+
case "boolean": return ["boolean"];
|
|
263
|
+
case "date": return ["date"];
|
|
264
|
+
case "string": return ["string", "enum"];
|
|
265
|
+
default: return Array.isArray(attribute.type) ? ["string", "enum"] : ["string"];
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/** The description of a contract field whose type Better Auth cannot use, or `undefined` when it can. */
|
|
269
|
+
function wrongTypeFound(field, accepted) {
|
|
270
|
+
if (field.type.kind !== "scalar" || field.many) return describeFieldType(field);
|
|
271
|
+
const kind = codecKind(field.type.codecId);
|
|
272
|
+
return kind === void 0 || accepted.includes(kind) ? void 0 : describeFieldType(field);
|
|
273
|
+
}
|
|
274
|
+
function isSqlModelStorage(storage) {
|
|
275
|
+
return typeof storage["table"] === "string" && typeof storage["namespaceId"] === "string";
|
|
276
|
+
}
|
|
277
|
+
function columnFacts(contract, found, field) {
|
|
278
|
+
const storage = found.model.storage;
|
|
279
|
+
if (!isSqlModelStorage(storage)) return {
|
|
280
|
+
hasDatabaseDefault: false,
|
|
281
|
+
hasCreateGenerator: false
|
|
282
|
+
};
|
|
283
|
+
const column = storage.fields[field]?.column ?? field;
|
|
284
|
+
return {
|
|
285
|
+
hasDatabaseDefault: (resolveStorageTable(contract.storage, storage.table, storage.namespaceId)?.table)?.columns[column]?.default !== void 0,
|
|
286
|
+
hasCreateGenerator: (contract.execution?.mutations.defaults ?? []).some(({ ref, onCreate }) => onCreate !== void 0 && ref.namespace === storage.namespaceId && ref.entry === storage.table && ref.field === column)
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
function compareFoundModel(contract, expected, found, idStrategy, problems) {
|
|
290
|
+
const fields = found.model.fields;
|
|
291
|
+
const model = found.name;
|
|
292
|
+
const missingFields = [];
|
|
293
|
+
const id = fields["id"];
|
|
294
|
+
if (id === void 0) missingFields.push("id");
|
|
295
|
+
else {
|
|
296
|
+
const wrong = wrongTypeFound(id, acceptedKindsByIdStrategy[idStrategy]);
|
|
297
|
+
if (wrong !== void 0) problems.push({
|
|
298
|
+
kind: "wrong-type",
|
|
299
|
+
model,
|
|
300
|
+
field: "id",
|
|
301
|
+
attribute: void 0,
|
|
302
|
+
reference: void 0,
|
|
303
|
+
found: wrong
|
|
304
|
+
});
|
|
305
|
+
const facts = columnFacts(contract, found, "id");
|
|
306
|
+
if ((idStrategy === "serial" || idStrategy === "contract") && !facts.hasDatabaseDefault && !facts.hasCreateGenerator) problems.push({
|
|
307
|
+
kind: "id-without-default",
|
|
308
|
+
model
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
for (const field of expected.fields) {
|
|
312
|
+
const contractField = fields[field.name];
|
|
313
|
+
if (contractField === void 0) {
|
|
314
|
+
missingFields.push(field.name);
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
const wrong = wrongTypeFound(contractField, acceptedKinds(field.attribute, idStrategy));
|
|
318
|
+
if (wrong !== void 0) problems.push({
|
|
319
|
+
kind: "wrong-type",
|
|
320
|
+
model,
|
|
321
|
+
field: field.name,
|
|
322
|
+
attribute: field.attribute,
|
|
323
|
+
reference: field.reference,
|
|
324
|
+
found: wrong
|
|
325
|
+
});
|
|
326
|
+
else if (mayBeNull(field.attribute) && !contractField.nullable) problems.push({
|
|
327
|
+
kind: "optional-field-not-nullable",
|
|
328
|
+
model,
|
|
329
|
+
field: field.name,
|
|
330
|
+
attribute: field.attribute,
|
|
331
|
+
reference: field.reference
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
for (const field of missingFields) problems.push({
|
|
335
|
+
kind: "missing-field",
|
|
336
|
+
model,
|
|
337
|
+
field
|
|
338
|
+
});
|
|
339
|
+
const written = /* @__PURE__ */ new Set(["id", ...expected.fields.map((field) => field.name)]);
|
|
340
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
341
|
+
if (written.has(name) || field.nullable) continue;
|
|
342
|
+
const facts = columnFacts(contract, found, name);
|
|
343
|
+
if (!facts.hasDatabaseDefault && !facts.hasCreateGenerator) problems.push({
|
|
344
|
+
kind: "required-field-not-written",
|
|
345
|
+
model,
|
|
346
|
+
field: name
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
return missingFields;
|
|
350
|
+
}
|
|
351
|
+
function hasUuidId(found) {
|
|
352
|
+
const id = found.model.fields["id"];
|
|
353
|
+
return id?.type.kind === "scalar" && codecKind(id.type.codecId) === "uuid";
|
|
354
|
+
}
|
|
355
|
+
function uuidKeyedModelsOf(models, referencedModels) {
|
|
356
|
+
const found = [...models.flatMap((model) => model.status === "found" ? [[model.expected.physicalName, model.found]] : []), ...referencedModels];
|
|
357
|
+
return new Set(found.filter(([, model]) => hasUuidId(model)).map(([name]) => name));
|
|
358
|
+
}
|
|
359
|
+
/** A model or field name that is not a Prisma identifier can be neither matched nor printed, so it is the only problem reported. */
|
|
360
|
+
function invalidNameProblems(models) {
|
|
361
|
+
return models.flatMap((model) => [...isPslIdentifier(model.physicalName) ? [] : [{
|
|
362
|
+
kind: "invalid-name",
|
|
363
|
+
model: model.physicalName
|
|
364
|
+
}], ...model.fields.filter((field) => !isPslIdentifier(field.name)).map((field) => ({
|
|
365
|
+
kind: "invalid-name",
|
|
366
|
+
model: model.physicalName,
|
|
367
|
+
field: field.name
|
|
368
|
+
}))]);
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Compares the contract with the models and fields Better Auth's table description asks for. The contract check and `auth generate` both use it.
|
|
372
|
+
*/
|
|
373
|
+
function compareContract(input) {
|
|
374
|
+
const { contract, betterAuthOptions, namespace } = input;
|
|
375
|
+
const idStrategy = idStrategyOf(betterAuthOptions);
|
|
376
|
+
const defaultNamespace = defaultNamespaceByTarget[contract.target] ?? UNBOUND_DOMAIN_NAMESPACE_ID;
|
|
377
|
+
const storageNamesIgnoreCase = storageNamesIgnoreCaseByTarget[contract.target] ?? false;
|
|
378
|
+
const expectedModelList = managedModels(input.tables, input);
|
|
379
|
+
const nameProblems = [...invalidNameProblems(expectedModelList), ...caseOnlyNameCollisions(betterAuthModels(input.tables, input)).map((models) => ({
|
|
380
|
+
kind: "colliding-model-names",
|
|
381
|
+
models
|
|
382
|
+
}))];
|
|
383
|
+
if (nameProblems.length > 0) return {
|
|
384
|
+
models: [],
|
|
385
|
+
problems: nameProblems,
|
|
386
|
+
referencedModels: /* @__PURE__ */ new Map(),
|
|
387
|
+
uuidKeyedModels: /* @__PURE__ */ new Set(),
|
|
388
|
+
idStrategy,
|
|
389
|
+
namespace,
|
|
390
|
+
defaultNamespace,
|
|
391
|
+
storageNamesIgnoreCase
|
|
392
|
+
};
|
|
393
|
+
const problems = [];
|
|
394
|
+
const models = [];
|
|
395
|
+
for (const expected of expectedModelList) {
|
|
396
|
+
const lookup = findModel(contract, expected.physicalName, namespace);
|
|
397
|
+
switch (lookup.kind) {
|
|
398
|
+
case "missing":
|
|
399
|
+
problems.push({
|
|
400
|
+
kind: "missing-model",
|
|
401
|
+
model: expected.physicalName
|
|
402
|
+
});
|
|
403
|
+
models.push({
|
|
404
|
+
status: "missing",
|
|
405
|
+
expected
|
|
406
|
+
});
|
|
407
|
+
break;
|
|
408
|
+
case "ambiguous":
|
|
409
|
+
problems.push({
|
|
410
|
+
kind: "ambiguous-model",
|
|
411
|
+
model: lookup.name,
|
|
412
|
+
namespaceIds: lookup.namespaceIds
|
|
413
|
+
});
|
|
414
|
+
models.push({
|
|
415
|
+
status: "ambiguous",
|
|
416
|
+
expected
|
|
417
|
+
});
|
|
418
|
+
break;
|
|
419
|
+
case "found": {
|
|
420
|
+
const missingFields = compareFoundModel(contract, expected, lookup, idStrategy, problems);
|
|
421
|
+
models.push({
|
|
422
|
+
status: "found",
|
|
423
|
+
expected,
|
|
424
|
+
found: lookup,
|
|
425
|
+
missingFields
|
|
426
|
+
});
|
|
427
|
+
break;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
const expectedNames = new Set(expectedModelList.map((model) => model.physicalName));
|
|
432
|
+
const referencedModels = /* @__PURE__ */ new Map();
|
|
433
|
+
for (const model of expectedModelList) for (const { reference } of model.fields) {
|
|
434
|
+
if (reference === void 0 || expectedNames.has(reference.model)) continue;
|
|
435
|
+
const lookup = findModel(contract, reference.model, namespace);
|
|
436
|
+
if (lookup.kind === "found") referencedModels.set(reference.model, lookup);
|
|
437
|
+
}
|
|
438
|
+
return {
|
|
439
|
+
models,
|
|
440
|
+
problems,
|
|
441
|
+
referencedModels,
|
|
442
|
+
uuidKeyedModels: acceptedKindsByIdStrategy[idStrategy].includes("uuid") ? uuidKeyedModelsOf(models, referencedModels) : /* @__PURE__ */ new Set(),
|
|
443
|
+
idStrategy,
|
|
444
|
+
namespace,
|
|
445
|
+
defaultNamespace,
|
|
446
|
+
storageNamesIgnoreCase
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
//#endregion
|
|
450
|
+
//#region src/contract/psl-types.ts
|
|
451
|
+
/** 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`. */
|
|
452
|
+
function pslTypeOf(attribute, reference, { idStrategy, uuidKeyedModels }) {
|
|
453
|
+
if (isIdReference(attribute)) {
|
|
454
|
+
if (reference !== void 0 && uuidKeyedModels.has(reference.model)) return "Uuid";
|
|
455
|
+
return idStrategy === "serial" ? "Int" : "String";
|
|
456
|
+
}
|
|
457
|
+
switch (attribute.type) {
|
|
458
|
+
case "number": return attribute.bigint === true ? "BigInt(as: number)" : "Int";
|
|
459
|
+
case "boolean": return "Boolean";
|
|
460
|
+
case "date": return "DateTime";
|
|
461
|
+
default: return "String";
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
/** The `id` field the printed PSL declares, as its columns. */
|
|
465
|
+
function idFieldOf(idStrategy) {
|
|
466
|
+
switch (idStrategy) {
|
|
467
|
+
case "serial": return {
|
|
468
|
+
name: "id",
|
|
469
|
+
type: "Int",
|
|
470
|
+
attributes: "@id @default(autoincrement())"
|
|
471
|
+
};
|
|
472
|
+
case "contract": return {
|
|
473
|
+
name: "id",
|
|
474
|
+
type: "String",
|
|
475
|
+
attributes: "@id @onCreate(uuid())"
|
|
476
|
+
};
|
|
477
|
+
default: return {
|
|
478
|
+
name: "id",
|
|
479
|
+
type: "String",
|
|
480
|
+
attributes: "@id"
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
function idLineOf(idStrategy) {
|
|
485
|
+
const { name, type, attributes } = idFieldOf(idStrategy);
|
|
486
|
+
return `${name} ${type} ${attributes}`;
|
|
487
|
+
}
|
|
488
|
+
//#endregion
|
|
489
|
+
//#region src/contract/print-psl.ts
|
|
490
|
+
const actionNames = {
|
|
491
|
+
cascade: "Cascade",
|
|
492
|
+
"no action": "NoAction",
|
|
493
|
+
restrict: "Restrict",
|
|
494
|
+
"set null": "SetNull",
|
|
495
|
+
"set default": "SetDefault"
|
|
496
|
+
};
|
|
497
|
+
function existingPrintedModel(found, betterAuthFields) {
|
|
498
|
+
return {
|
|
499
|
+
name: found.name,
|
|
500
|
+
namespaceId: found.namespaceId,
|
|
501
|
+
existing: true,
|
|
502
|
+
physicalName: void 0,
|
|
503
|
+
table: void 0,
|
|
504
|
+
columns: [],
|
|
505
|
+
taken: /* @__PURE__ */ new Set([
|
|
506
|
+
...betterAuthFields,
|
|
507
|
+
...Object.keys(found.model.fields),
|
|
508
|
+
...Object.keys(found.model.relations)
|
|
509
|
+
]),
|
|
510
|
+
fields: [],
|
|
511
|
+
backRelations: [],
|
|
512
|
+
attributes: []
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
function printedModelFor(model, comparison) {
|
|
516
|
+
const betterAuthFields = ["id", ...model.expected.fields.map((field) => field.name)];
|
|
517
|
+
switch (model.status) {
|
|
518
|
+
case "missing": return {
|
|
519
|
+
name: upperFirst(model.expected.physicalName),
|
|
520
|
+
namespaceId: comparison.namespace ?? comparison.defaultNamespace,
|
|
521
|
+
existing: false,
|
|
522
|
+
physicalName: model.expected.physicalName,
|
|
523
|
+
table: model.expected.physicalName,
|
|
524
|
+
columns: [],
|
|
525
|
+
taken: new Set(betterAuthFields),
|
|
526
|
+
fields: [],
|
|
527
|
+
backRelations: [],
|
|
528
|
+
attributes: []
|
|
529
|
+
};
|
|
530
|
+
case "found": return existingPrintedModel(model.found, betterAuthFields);
|
|
531
|
+
case "ambiguous": return;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
function typeName(of, from) {
|
|
535
|
+
return of.namespaceId === from.namespaceId ? of.name : `${of.namespaceId}.${of.name}`;
|
|
536
|
+
}
|
|
537
|
+
function scalarLine(field, comparison) {
|
|
538
|
+
const optional = field.attribute.required === false ? "?" : "";
|
|
539
|
+
const type = `${pslTypeOf(field.attribute, field.reference, comparison)}${optional}`;
|
|
540
|
+
return field.attribute.unique === true ? [
|
|
541
|
+
field.name,
|
|
542
|
+
type,
|
|
543
|
+
"@unique"
|
|
544
|
+
] : [field.name, type];
|
|
545
|
+
}
|
|
546
|
+
function idLine(comparison) {
|
|
547
|
+
const { name, type, attributes } = idFieldOf(comparison.idStrategy);
|
|
548
|
+
return [
|
|
549
|
+
name,
|
|
550
|
+
type,
|
|
551
|
+
attributes
|
|
552
|
+
];
|
|
553
|
+
}
|
|
554
|
+
function freeName(name, printed) {
|
|
555
|
+
let free = name;
|
|
556
|
+
while (printed.taken.has(free)) free = `${free}_`;
|
|
557
|
+
return free;
|
|
558
|
+
}
|
|
559
|
+
function relationFieldName(foreignKey, holder) {
|
|
560
|
+
const stripped = foreignKey.endsWith("Id") ? foreignKey.slice(0, -2) : foreignKey;
|
|
561
|
+
return stripped === "" || stripped === foreignKey || holder.taken.has(stripped) ? freeName(`${foreignKey}Relation`, holder) : stripped;
|
|
562
|
+
}
|
|
563
|
+
function foreignKeyCount(expected, referenced) {
|
|
564
|
+
return expected.fields.filter((field) => field.reference?.model === referenced).length;
|
|
565
|
+
}
|
|
566
|
+
function indexLines(expected) {
|
|
567
|
+
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(", ")}])`)];
|
|
568
|
+
return [...new Set(lines)];
|
|
569
|
+
}
|
|
570
|
+
function alignedLines(lines) {
|
|
571
|
+
const nameWidth = Math.max(0, ...lines.map(([name]) => name.length));
|
|
572
|
+
const typeWidth = Math.max(0, ...lines.map(([, type]) => type.length));
|
|
573
|
+
return lines.map(([name, type, attributes]) => attributes === void 0 || attributes === "" ? `${name.padEnd(nameWidth)} ${type}` : `${name.padEnd(nameWidth)} ${type.padEnd(typeWidth)} ${attributes}`);
|
|
574
|
+
}
|
|
575
|
+
function blockText(block, indent) {
|
|
576
|
+
const body = [...block.fieldLines.map((line) => ` ${line}`)];
|
|
577
|
+
if (block.attributeLines.length > 0) body.push("", ...block.attributeLines.map((line) => ` ${line}`));
|
|
578
|
+
return [
|
|
579
|
+
`model ${block.modelName} {`,
|
|
580
|
+
...body,
|
|
581
|
+
"}"
|
|
582
|
+
].map((line) => line === "" ? "" : `${indent}${line}`).join("\n");
|
|
583
|
+
}
|
|
584
|
+
/** PSL text for printed blocks; blocks of missing models go inside a `namespace` block when the adapter's `namespace` option is set. */
|
|
585
|
+
function renderBlocks(blocks, namespace) {
|
|
586
|
+
const chunks = [];
|
|
587
|
+
let run = [];
|
|
588
|
+
const flush = () => {
|
|
589
|
+
if (run.length === 0) return;
|
|
590
|
+
const inner = run.map((block) => blockText(block, " ")).join("\n\n");
|
|
591
|
+
chunks.push(`namespace ${namespace} {\n${inner}\n}`);
|
|
592
|
+
run = [];
|
|
593
|
+
};
|
|
594
|
+
for (const block of blocks) {
|
|
595
|
+
if (namespace !== void 0 && !block.existing) {
|
|
596
|
+
run.push(block);
|
|
597
|
+
continue;
|
|
598
|
+
}
|
|
599
|
+
flush();
|
|
600
|
+
chunks.push(blockText(block, ""));
|
|
601
|
+
}
|
|
602
|
+
flush();
|
|
603
|
+
return chunks.join("\n\n");
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* 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.
|
|
607
|
+
*/
|
|
608
|
+
function printPsl(comparison) {
|
|
609
|
+
const printedModels = /* @__PURE__ */ new Map();
|
|
610
|
+
for (const model of comparison.models) {
|
|
611
|
+
const printed = printedModelFor(model, comparison);
|
|
612
|
+
if (printed !== void 0) printedModels.set(model.expected.physicalName, printed);
|
|
613
|
+
}
|
|
614
|
+
for (const [physicalName, found] of comparison.referencedModels) printedModels.set(physicalName, existingPrintedModel(found, []));
|
|
615
|
+
const notes = [];
|
|
616
|
+
for (const model of comparison.models) {
|
|
617
|
+
const holder = printedModels.get(model.expected.physicalName);
|
|
618
|
+
if (holder === void 0) continue;
|
|
619
|
+
if (model.status === "found") {
|
|
620
|
+
for (const name of model.missingFields) {
|
|
621
|
+
const field = model.expected.fields.find((candidate) => candidate.name === name);
|
|
622
|
+
holder.fields.push(field === void 0 ? idLine(comparison) : scalarLine(field, comparison));
|
|
623
|
+
holder.columns.push(name);
|
|
624
|
+
}
|
|
625
|
+
continue;
|
|
626
|
+
}
|
|
627
|
+
holder.fields.push(idLine(comparison));
|
|
628
|
+
for (const field of model.expected.fields) {
|
|
629
|
+
holder.fields.push(scalarLine(field, comparison));
|
|
630
|
+
const reference = field.reference;
|
|
631
|
+
if (reference === void 0) continue;
|
|
632
|
+
const referenced = printedModels.get(reference.model);
|
|
633
|
+
const optional = field.attribute.required === false;
|
|
634
|
+
let action = reference.onDelete;
|
|
635
|
+
if (action === "set null" && !optional || action === "set default") {
|
|
636
|
+
notes.push(`${holder.name}.${field.name}: Better Auth asks for onDelete ${action}, which needs ${action === "set null" ? "an optional field" : "a default"}; NoAction is used instead`);
|
|
637
|
+
action = "no action";
|
|
638
|
+
}
|
|
639
|
+
const relationName = relationFieldName(field.name, holder);
|
|
640
|
+
holder.taken.add(relationName);
|
|
641
|
+
let relationLabel;
|
|
642
|
+
if (referenced !== void 0) {
|
|
643
|
+
const list = field.attribute.unique !== true;
|
|
644
|
+
const base = `${lowerFirst(holder.name)}${list ? "s" : ""}`;
|
|
645
|
+
const named = referenced.taken.has(base) || foreignKeyCount(model.expected, reference.model) > 1;
|
|
646
|
+
const backName = named ? freeName(`${base}By${upperFirst(field.name)}`, referenced) : base;
|
|
647
|
+
relationLabel = named ? `"${holder.name}_${field.name}"` : void 0;
|
|
648
|
+
referenced.taken.add(backName);
|
|
649
|
+
referenced.backRelations.push([
|
|
650
|
+
backName,
|
|
651
|
+
`${typeName(holder, referenced)}${list ? "[]" : "?"}`,
|
|
652
|
+
relationLabel === void 0 ? void 0 : `@relation(${relationLabel})`
|
|
653
|
+
]);
|
|
654
|
+
}
|
|
655
|
+
const referencedType = referenced === void 0 ? upperFirst(reference.model) : typeName(referenced, holder);
|
|
656
|
+
const relationArguments = [
|
|
657
|
+
...relationLabel === void 0 ? [] : [relationLabel],
|
|
658
|
+
`fields: [${field.name}]`,
|
|
659
|
+
`references: [${reference.field}]`,
|
|
660
|
+
`onDelete: ${actionNames[action]}`
|
|
661
|
+
].join(", ");
|
|
662
|
+
holder.fields.push([
|
|
663
|
+
relationName,
|
|
664
|
+
`${referencedType}${optional ? "?" : ""}`,
|
|
665
|
+
`@relation(${relationArguments})`
|
|
666
|
+
]);
|
|
667
|
+
}
|
|
668
|
+
holder.attributes.push(...indexLines(model.expected), `@@map("${model.expected.physicalName}")`);
|
|
669
|
+
}
|
|
670
|
+
const blocks = [];
|
|
671
|
+
for (const printed of printedModels.values()) {
|
|
672
|
+
const lines = [...printed.fields, ...printed.backRelations];
|
|
673
|
+
if (lines.length === 0) continue;
|
|
674
|
+
blocks.push({
|
|
675
|
+
modelName: printed.name,
|
|
676
|
+
namespaceId: printed.namespaceId,
|
|
677
|
+
existing: printed.existing,
|
|
678
|
+
physicalName: printed.physicalName,
|
|
679
|
+
table: printed.table,
|
|
680
|
+
columns: printed.columns,
|
|
681
|
+
fieldNames: lines.map(([name]) => name),
|
|
682
|
+
fieldLines: alignedLines(lines),
|
|
683
|
+
attributeLines: printed.attributes
|
|
684
|
+
});
|
|
685
|
+
}
|
|
686
|
+
return {
|
|
687
|
+
blocks,
|
|
688
|
+
notes,
|
|
689
|
+
text: renderBlocks(blocks, comparison.namespace)
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
//#endregion
|
|
693
|
+
//#region src/contract/message.ts
|
|
694
|
+
function section(title, lines) {
|
|
695
|
+
return lines.length === 0 ? [] : [
|
|
696
|
+
`${title}:`,
|
|
697
|
+
"",
|
|
698
|
+
...lines.map((line) => ` ${line}`),
|
|
699
|
+
""
|
|
700
|
+
];
|
|
701
|
+
}
|
|
702
|
+
function changeLines(comparison) {
|
|
703
|
+
const lines = [];
|
|
704
|
+
const idLinesPrinted = /* @__PURE__ */ new Set();
|
|
705
|
+
for (const problem of comparison.problems) switch (problem.kind) {
|
|
706
|
+
case "ambiguous-model":
|
|
707
|
+
lines.push(ambiguousModelMessage(problem.model, problem.namespaceIds));
|
|
708
|
+
break;
|
|
709
|
+
case "optional-field-not-nullable":
|
|
710
|
+
lines.push(`${problem.model}.${problem.field}: must be \`${pslTypeOf(problem.attribute, problem.reference, comparison)}?\`, because Better Auth can write null to it`);
|
|
711
|
+
break;
|
|
712
|
+
case "id-without-default":
|
|
713
|
+
case "wrong-type":
|
|
714
|
+
if (problem.kind === "id-without-default" || problem.attribute === void 0) {
|
|
715
|
+
if (idLinesPrinted.has(problem.model)) break;
|
|
716
|
+
idLinesPrinted.add(problem.model);
|
|
717
|
+
lines.push(`${problem.model}.id: must be \`${idLineOf(comparison.idStrategy)}\``);
|
|
718
|
+
break;
|
|
719
|
+
}
|
|
720
|
+
lines.push(`${problem.model}.${problem.field}: must be \`${pslTypeOf(problem.attribute, problem.reference, comparison)}${mayBeNull(problem.attribute) ? "?" : ""}\` (found ${problem.found})`);
|
|
721
|
+
break;
|
|
722
|
+
}
|
|
723
|
+
return lines;
|
|
724
|
+
}
|
|
725
|
+
function unwrittenLines(comparison) {
|
|
726
|
+
return comparison.problems.flatMap((problem) => problem.kind === "required-field-not-written" ? [`${problem.model}.${problem.field}: make it optional or give it a default`] : []);
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* The message the contract check and `auth generate` report, or `undefined` when the contract holds everything Better Auth needs.
|
|
730
|
+
*/
|
|
731
|
+
function contractMessage(comparison) {
|
|
732
|
+
if (comparison.problems.length === 0) return void 0;
|
|
733
|
+
const invalidNames = comparison.problems.flatMap((problem) => {
|
|
734
|
+
if (problem.kind === "colliding-model-names") return [caseOnlyNameCollisionMessage(problem.models)];
|
|
735
|
+
if (problem.kind !== "invalid-name") return [];
|
|
736
|
+
const message = problem.field === void 0 ? invalidModelNameMessage(problem.model) : invalidFieldNameMessage(problem.model, problem.field);
|
|
737
|
+
return message === void 0 ? [] : [message];
|
|
738
|
+
});
|
|
739
|
+
if (invalidNames.length > 0) return invalidNames.join("\n");
|
|
740
|
+
const psl = printPsl(comparison);
|
|
741
|
+
const additions = psl.text === "" ? [] : [
|
|
742
|
+
"Add to your contract:",
|
|
743
|
+
"",
|
|
744
|
+
psl.text,
|
|
745
|
+
""
|
|
746
|
+
];
|
|
747
|
+
return [
|
|
748
|
+
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.",
|
|
749
|
+
"",
|
|
750
|
+
...additions,
|
|
751
|
+
...section("Change in your contract", changeLines(comparison)),
|
|
752
|
+
...section("Fields Better Auth does not write", unwrittenLines(comparison)),
|
|
753
|
+
...section("Notes", psl.notes),
|
|
754
|
+
"Then run `prisma contract emit` and update your database."
|
|
755
|
+
].join("\n");
|
|
756
|
+
}
|
|
757
|
+
//#endregion
|
|
758
|
+
//#region src/contract/contract-check.ts
|
|
759
|
+
/** The error the contract check rejects with and `createSchema` throws. Its `code` is what Better Auth's CLI looks for. */
|
|
760
|
+
function contractMismatchError(message) {
|
|
761
|
+
return Object.assign(new BetterAuthError(message), { code: "SCHEMA_MISMATCH" });
|
|
762
|
+
}
|
|
763
|
+
/** The mismatch error for a contract, or `undefined` when it holds everything Better Auth needs. */
|
|
764
|
+
function contractMismatch(input) {
|
|
765
|
+
const message = contractMessage(compareContract(input));
|
|
766
|
+
return message === void 0 ? void 0 : contractMismatchError(message);
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* 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.
|
|
770
|
+
*/
|
|
771
|
+
function createContractCheck(input) {
|
|
772
|
+
let verdict;
|
|
773
|
+
return () => {
|
|
774
|
+
if (verdict === void 0) try {
|
|
775
|
+
const error = contractMismatch(input());
|
|
776
|
+
verdict = error === void 0 ? { clean: true } : {
|
|
777
|
+
clean: false,
|
|
778
|
+
error
|
|
779
|
+
};
|
|
780
|
+
} catch (error) {
|
|
781
|
+
verdict = {
|
|
782
|
+
clean: false,
|
|
783
|
+
error
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
return verdict.clean ? void 0 : Promise.reject(verdict.error);
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
/**
|
|
790
|
+
* 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.
|
|
791
|
+
*/
|
|
792
|
+
function registerContractCheck(adapter, check, betterAuthOptions) {
|
|
793
|
+
if (typeof internal.registerSchemaCheck !== "function") return;
|
|
794
|
+
internal.registerSchemaCheck(adapter, check, { runtimeEnabled: betterAuthOptions.advanced?.database?.validateSchema !== false });
|
|
795
|
+
}
|
|
796
|
+
//#endregion
|
|
797
|
+
export { assertFieldName as _, printPsl as a, describeFieldType as c, caseOnlyNameCollisions as d, ambiguousModelMessage as f, modelNameCandidates as g, missingModelMessage as h, contractMessage as i, codecKind as l, isSearchedNamespace as m, createContractCheck as n, renderBlocks as o, findModel as p, registerContractCheck as r, compareContract as s, contractMismatchError as t, betterAuthModels as u, assertModelName as v, caseOnlyNameCollisionMessage as y };
|
|
798
|
+
|
|
799
|
+
//# sourceMappingURL=contract-check-Cw4rCQvX.mjs.map
|