@prisma/orm-better-auth 8.0.0-rc.25-dev.8 → 8.0.0-rc.25-dev.10
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
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/models/identifiers.ts","../src/models/model-lookup.ts","../src/orm.ts","../src/collections.ts","../src/models/better-auth-models.ts","../src/models/codec-kinds.ts","../src/models/field-type.ts","../src/contract/compare.ts","../src/contract/psl-types.ts","../src/contract/print-psl.ts","../src/contract/message.ts","../src/contract/contract-check.ts","../src/filters.ts","../src/joins.ts","../src/adapter.ts"],"sourcesContent":["import { BetterAuthError } from '@better-auth/core/error';\n\nconst pslIdentifier = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nexport function isPslIdentifier(name: string): boolean {\n return pslIdentifier.test(name);\n}\n\n/** The message for a Better Auth model name that is not a Prisma identifier, or `undefined` when it is one. */\nexport function invalidModelNameMessage(name: string): string | undefined {\n if (isPslIdentifier(name)) return undefined;\n 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.`;\n}\n\n/** The message for a Better Auth field name that is not a Prisma identifier, or `undefined` when it is one. */\nexport function invalidFieldNameMessage(model: string, field: string): string | undefined {\n if (isPslIdentifier(field)) return undefined;\n 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.`;\n}\n\n/** The message for Better Auth models whose names differ only in the case of the first letter. */\nexport function caseOnlyNameCollisionMessage(names: readonly string[]): string {\n const quoted = names.map((name) => `\"${name}\"`);\n const listed = `${quoted.slice(0, -1).join(', ')} and ${quoted.at(-1)}`;\n return `Better Auth's models ${listed} 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.`;\n}\n\nexport function assertModelName(name: string): void {\n const message = invalidModelNameMessage(name);\n if (message !== undefined) throw new BetterAuthError(message);\n}\n\nexport function assertFieldName(model: string, field: string): void {\n const message = invalidFieldNameMessage(model, field);\n if (message !== undefined) throw new BetterAuthError(message);\n}\n\nexport function upperFirst(name: string): string {\n return name.charAt(0).toUpperCase() + name.slice(1);\n}\n\nexport function lowerFirst(name: string): string {\n return name.charAt(0).toLowerCase() + name.slice(1);\n}\n","import type { SqlStorage } from '@prisma/orm-family-sql/contract/types';\nimport type { Contract, ContractModelBase } from '@prisma/orm-framework/contract/types';\nimport { upperFirst } from './identifiers';\n\nexport type SqlContract = Contract<SqlStorage>;\n\nexport interface FoundModel {\n readonly kind: 'found';\n readonly name: string;\n readonly namespaceId: string;\n readonly model: ContractModelBase;\n}\n\nexport interface MissingModel {\n readonly kind: 'missing';\n}\n\nexport interface AmbiguousModel {\n readonly kind: 'ambiguous';\n readonly name: string;\n readonly namespaceIds: readonly string[];\n}\n\nexport type ModelLookup = FoundModel | MissingModel | AmbiguousModel;\n\nexport function missingModelMessage(physicalName: string): string {\n return `Model \"${physicalName}\" is not in your Prisma contract. Run \\`npx auth@latest generate\\` to see what to add.`;\n}\n\nexport function ambiguousModelMessage(name: string, namespaceIds: readonly string[]): string {\n return `Model \"${name}\" is in more than one namespace of your Prisma contract (${namespaceIds.join(', ')}). Set the adapter's \"namespace\" option.`;\n}\n\n/**\n * 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.\n */\nexport function findModel(\n contract: SqlContract,\n physicalName: string,\n namespace: string | undefined,\n): ModelLookup {\n const namespaces = contract.domain.namespaces;\n const searched =\n namespace === undefined\n ? Object.keys(namespaces)\n : [namespace].filter((id) => Object.hasOwn(namespaces, id));\n const candidates = [...new Set([physicalName, upperFirst(physicalName)])];\n for (const name of candidates) {\n const hits = searched.filter((id) => Object.hasOwn(namespaces[id]?.models ?? {}, name)).sort();\n const [only] = hits;\n if (hits.length > 1) return { kind: 'ambiguous', name, namespaceIds: hits };\n const model = only === undefined ? undefined : namespaces[only]?.models[name];\n if (only !== undefined && model !== undefined) {\n return { kind: 'found', name, namespaceId: only, model };\n }\n }\n return { kind: 'missing' };\n}\n","import type { and } from '@prisma/orm-family-sql/orm-client';\nimport { blindCast } from '@prisma/orm-framework/utils/casts';\n\n/** A filter the ORM client's `and`, `or` and `where` accept. */\nexport type Condition = Parameters<typeof and>[number];\n\nexport type Row = Record<string, unknown>;\n\n/** A raw SQL expression built with `fns.raw`, before its codec is named. */\nexport interface RawExpression {\n returns(codecId: string): unknown;\n}\n\nexport interface WhereFunctions {\n raw(strings: TemplateStringsArray, ...values: unknown[]): RawExpression;\n eq(left: unknown, right: unknown): unknown;\n ne(left: unknown, right: unknown): unknown;\n}\n\nexport interface WhereTools {\n readonly fns: WhereFunctions;\n}\n\n/** The model accessor a `where` or `orderBy` callback receives. Its properties are the model's fields. */\nexport type ModelAccessor = object;\n\n/**\n * The part of an ORM client collection the adapter calls. The adapter reaches collections by run-time model name, so their contract types are not known here.\n */\nexport interface OrmCollection {\n where(filter: (model: ModelAccessor, tools: WhereTools) => Condition): OrmCollection;\n select(...fields: string[]): OrmCollection;\n orderBy(selector: (model: ModelAccessor) => unknown): OrmCollection;\n limit(count: number): OrmCollection;\n offset(count: number): OrmCollection;\n include(relation: string, refine?: (related: OrmCollection) => OrmCollection): OrmCollection;\n first(): Promise<Row | null>;\n all(): PromiseLike<Row[]>;\n aggregate(\n build: (aggregates: { count(): unknown }) => Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n create(data: Row): Promise<Row>;\n update(data: Row): Promise<Row | null>;\n updateAndCount(data: Row): Promise<number>;\n deleteAndCount(): Promise<number>;\n}\n\nconst collectionMethods = [\n 'where',\n 'select',\n 'orderBy',\n 'limit',\n 'offset',\n 'include',\n 'first',\n 'all',\n 'aggregate',\n 'create',\n 'update',\n 'updateAndCount',\n 'deleteAndCount',\n] as const satisfies readonly (keyof OrmCollection)[];\n\nexport function isOrmCollection(value: unknown): value is OrmCollection {\n return (\n typeof value === 'object' &&\n value !== null &&\n collectionMethods.every((method) => typeof Reflect.get(value, method) === 'function')\n );\n}\n\n/** A property of an ORM client proxy, read by run-time name. */\nexport function property(target: unknown, name: string): unknown {\n return typeof target === 'object' && target !== null ? Reflect.get(target, name) : undefined;\n}\n\n/** Calls a method of an ORM client object by run-time name, or returns `undefined` when it has none. */\nexport function callMethod(target: unknown, name: string, ...args: unknown[]): unknown {\n const method = property(target, name);\n if (typeof method !== 'function') return undefined;\n return Reflect.apply(method, target, args);\n}\n\nexport function hasMethod(target: unknown, name: string): boolean {\n return typeof property(target, name) === 'function';\n}\n\n/** A filter built by calling the ORM client's field and `fns` methods by run-time name. */\nexport function asCondition(value: unknown): Condition {\n return blindCast<\n Condition,\n 'field and fns methods are called by run-time name, so their filter results arrive untyped; each comes from an ORM client method that returns a filter'\n >(value);\n}\n","import { BetterAuthError } from '@better-auth/core/error';\nimport { UNBOUND_DOMAIN_NAMESPACE_ID } from '@prisma/orm-framework/contract/default-namespace';\nimport { assertModelName } from './models/identifiers';\nimport {\n ambiguousModelMessage,\n type FoundModel,\n findModel,\n missingModelMessage,\n type SqlContract,\n} from './models/model-lookup';\nimport { isOrmCollection, type OrmCollection, property } from './orm';\n\nexport interface ModelCollections {\n /** The contract model for a Better Auth physical model name; raises a `BetterAuthError` when the name is not an identifier, or when no model or more than one has it. */\n model(physicalName: string): FoundModel;\n /** The model's collection on an ORM client root: the client's, or a transaction's. */\n collection(orm: object, model: FoundModel): OrmCollection;\n}\n\n/** Finds each model once per adapter instance, and its collection on the ORM client root a call uses. */\nexport function createModelCollections(\n contract: SqlContract,\n namespace: string | undefined,\n): ModelCollections {\n const found = new Map<string, FoundModel>();\n const namespaceIds = Object.keys(contract.domain.namespaces);\n const flat = namespaceIds.length === 1 && namespaceIds[0] === UNBOUND_DOMAIN_NAMESPACE_ID;\n return {\n model(physicalName) {\n const known = found.get(physicalName);\n if (known !== undefined) return known;\n assertModelName(physicalName);\n const lookup = findModel(contract, physicalName, namespace);\n if (lookup.kind === 'ambiguous') {\n throw new BetterAuthError(ambiguousModelMessage(lookup.name, lookup.namespaceIds));\n }\n if (lookup.kind === 'missing') throw new BetterAuthError(missingModelMessage(physicalName));\n found.set(physicalName, lookup);\n return lookup;\n },\n collection(orm, model) {\n const facet = flat ? orm : property(orm, model.namespaceId);\n const collection = property(facet, model.name);\n if (!isOrmCollection(collection)) {\n throw new BetterAuthError(missingModelMessage(model.name));\n }\n return collection;\n },\n };\n}\n","import type { BetterAuthOptions } from '@better-auth/core';\nimport type { BetterAuthDBSchema, DBFieldAttribute } from '@better-auth/core/db';\nimport { upperFirst } from './identifiers';\n\nexport type ReferentialAction = NonNullable<\n NonNullable<DBFieldAttribute['references']>['onDelete']\n>;\n\nexport interface BetterAuthReference {\n readonly model: string;\n readonly field: string;\n readonly onDelete: ReferentialAction;\n}\n\nexport interface BetterAuthField {\n readonly name: string;\n readonly attribute: DBFieldAttribute;\n readonly reference: BetterAuthReference | undefined;\n}\n\nexport interface BetterAuthIndex {\n readonly fields: readonly string[];\n readonly unique: boolean;\n}\n\n/** A model Better Auth calls, after `usePlural` and with tables that share a physical name merged. Its fields do not include `id`. */\nexport interface BetterAuthModel {\n /** Better Auth's name for the model after `modelName` and `usePlural`. It is matched to a contract model name, never to a table name. */\n readonly physicalName: string;\n readonly fields: readonly BetterAuthField[];\n readonly indexes: readonly BetterAuthIndex[];\n /** Whether the model is part of the schema Better Auth manages: false when every table merged into it is marked `disableMigrations`, or is the session table while sessions live in secondary storage. */\n readonly managed: boolean;\n}\n\nexport interface BetterAuthModelsOptions {\n readonly betterAuthOptions: BetterAuthOptions;\n readonly usePlural: boolean;\n}\n\ntype Table = BetterAuthDBSchema[string];\n\ninterface MergedModel {\n readonly fields: Map<string, BetterAuthField>;\n readonly indexes: BetterAuthIndex[];\n managed: boolean;\n}\n\nfunction physicalName(modelName: string, usePlural: boolean): string {\n return usePlural ? `${modelName}s` : modelName;\n}\n\nfunction isOmitted(key: string, table: Table, options: BetterAuthOptions): boolean {\n if (table.disableMigrations === true) return true;\n return (\n key === 'session' &&\n options.secondaryStorage !== undefined &&\n options.session?.storeSessionInDatabase !== true\n );\n}\n\nfunction referencedTable(tables: BetterAuthDBSchema, model: string): Table | undefined {\n return tables[model] ?? Object.values(tables).find((table) => table.modelName === model);\n}\n\nfunction resolveReference(\n tables: BetterAuthDBSchema,\n references: NonNullable<DBFieldAttribute['references']>,\n usePlural: boolean,\n): BetterAuthReference {\n const table = referencedTable(tables, references.model);\n const field = table?.fields[references.field];\n return {\n model: physicalName(table?.modelName ?? references.model, usePlural),\n field: field?.fieldName || references.field,\n onDelete: references.onDelete ?? 'cascade',\n };\n}\n\n/**\n * 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.\n */\nexport function betterAuthModels(\n tables: BetterAuthDBSchema,\n { betterAuthOptions, usePlural }: BetterAuthModelsOptions,\n): BetterAuthModel[] {\n const merged = new Map<string, MergedModel>();\n for (const [key, table] of Object.entries(tables)) {\n const name = physicalName(table.modelName, usePlural);\n const model: MergedModel = merged.get(name) ?? {\n fields: new Map(),\n indexes: [],\n managed: false,\n };\n model.managed ||= !isOmitted(key, table, betterAuthOptions);\n merged.set(name, model);\n for (const [fieldKey, attribute] of Object.entries(table.fields)) {\n const fieldName = attribute.fieldName || fieldKey;\n if (fieldName === 'id') continue;\n model.fields.set(fieldName, {\n name: fieldName,\n attribute,\n reference:\n attribute.references === undefined\n ? undefined\n : resolveReference(tables, attribute.references, usePlural),\n });\n }\n for (const index of table.indexes ?? []) {\n model.indexes.push({\n fields: index.fields.map((field) => table.fields[field]?.fieldName || field),\n unique: index.unique === true,\n });\n }\n }\n return [...merged].map(([name, { fields, indexes, managed }]) => ({\n physicalName: name,\n fields: [...fields.values()],\n indexes,\n managed,\n }));\n}\n\n/** Groups of physical model names that differ only in the case of the first letter, which the adapter refuses. */\nexport function caseOnlyNameCollisions(models: readonly BetterAuthModel[]): string[][] {\n const byModelName = new Map<string, string[]>();\n for (const { physicalName } of models) {\n const name = upperFirst(physicalName);\n byModelName.set(name, [...(byModelName.get(name) ?? []), physicalName]);\n }\n return [...byModelName.values()].filter((names) => names.length > 1);\n}\n\n/** The models of the schema Better Auth manages, which the comparison checks. */\nexport function managedModels(\n tables: BetterAuthDBSchema,\n options: BetterAuthModelsOptions,\n): BetterAuthModel[] {\n return betterAuthModels(tables, options).filter((model) => model.managed);\n}\n\n/**\n * Who gives `id` its value. Better Auth sends a string (`string`) or a UUID string (`uuid`); or it sends none and the contract fills it, with an autoincrement number (`serial`) or with a database default or an `onCreate` generator (`contract`).\n */\nexport type IdStrategy = 'string' | 'uuid' | 'serial' | 'contract';\n\nexport function idStrategyOf(options: BetterAuthOptions): IdStrategy {\n const generateId = options.advanced?.database?.generateId;\n if (generateId === 'serial') return 'serial';\n if (generateId === 'uuid') return 'uuid';\n if (generateId === false) return 'contract';\n return 'string';\n}\n\n/** 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. */\nexport function mayBeNull(attribute: DBFieldAttribute): boolean {\n return attribute.required === false;\n}\n\nexport function isIdReference(attribute: DBFieldAttribute): boolean {\n return attribute.references?.field === 'id';\n}\n","const codecKinds = ['string', 'enum', 'uuid', 'date', 'number', 'boolean', 'other'] as const;\n\nexport type CodecKind = (typeof codecKinds)[number];\n\nconst codecIdsByKind: Readonly<Record<CodecKind, readonly string[]>> = {\n string: ['pg/text@1', 'sql/varchar@1', 'sql/char@1', 'sqlite/text@1'],\n enum: ['pg/enum@1'],\n uuid: ['pg/uuid@1'],\n date: ['pg/timestamptz-date@1', 'pg/timestamp-date@1', 'sqlite/datetime@1'],\n number: [\n 'pg/int2@1',\n 'pg/int4@1',\n 'pg/int8number@1',\n 'pg/float4@1',\n 'pg/float8@1',\n 'sqlite/integer@1',\n 'sqlite/real@1',\n ],\n boolean: ['pg/bool@1', 'sqlite/boolean@1'],\n other: [\n 'pg/int8@1',\n 'pg/unboundedint@1',\n 'pg/numeric@1',\n 'pg/timestamptz-temporal@1',\n 'pg/timestamptz-string@1',\n 'pg/timestamp-temporal@1',\n 'pg/timestamp-string@1',\n 'pg/timestamp-instant@1',\n 'pg/date-temporal@1',\n 'pg/date-string@1',\n 'pg/time-temporal@1',\n 'pg/time-string@1',\n 'pg/timetz@1',\n 'pg/inet@1',\n 'pg/interval@1',\n 'pg/interval-string@1',\n 'pg/bit@1',\n 'pg/varbit@1',\n 'pg/xml@1',\n 'pg/oid@1',\n 'pg/money@1',\n 'pg/json@1',\n 'pg/jsonb@1',\n 'pg/bytea@1',\n 'sqlite/bigint@1',\n 'sqlite/decimal@1',\n 'sqlite/datetime-temporal@1',\n 'sqlite/datetime-string@1',\n 'sqlite/date-string@1',\n 'sqlite/date-temporal@1',\n 'sqlite/time-string@1',\n 'sqlite/time-temporal@1',\n 'sqlite/duration-string@1',\n 'sqlite/json@1',\n 'sqlite/blob@1',\n ],\n};\n\nconst kindByCodecId: ReadonlyMap<string, CodecKind> = new Map(\n codecKinds.flatMap((kind) => codecIdsByKind[kind].map((id): [string, CodecKind] => [id, kind])),\n);\n\n/** The kind of JavaScript value a codec reads and writes, or `undefined` for a codec this table does not know. */\nexport function codecKind(codecId: string): CodecKind | undefined {\n return kindByCodecId.get(codecId);\n}\n","import type { ContractField } from '@prisma/orm-framework/contract/types';\n\n/** What a contract field holds, as messages name it: its codec id, `<codec id> list`, `a value object` or `a union`. */\nexport function describeFieldType(field: ContractField): string {\n if (field.type.kind === 'valueObject') return 'a value object';\n if (field.type.kind === 'union') return 'a union';\n return field.many ? `${field.type.codecId} list` : field.type.codecId;\n}\n","import type { BetterAuthOptions } from '@better-auth/core';\nimport type { BetterAuthDBSchema, DBFieldAttribute } from '@better-auth/core/db';\nimport { resolveStorageTable } from '@prisma/orm-family-sql/contract/resolve-storage-table';\nimport type { SqlModelStorage } from '@prisma/orm-family-sql/contract/types';\nimport { UNBOUND_DOMAIN_NAMESPACE_ID } from '@prisma/orm-framework/contract/default-namespace';\nimport type { ContractField, ContractModelBase } from '@prisma/orm-framework/contract/types';\nimport {\n type BetterAuthModel,\n type BetterAuthReference,\n betterAuthModels,\n caseOnlyNameCollisions,\n type IdStrategy,\n idStrategyOf,\n isIdReference,\n managedModels,\n mayBeNull,\n} from '../models/better-auth-models';\nimport { type CodecKind, codecKind } from '../models/codec-kinds';\nimport { describeFieldType } from '../models/field-type';\nimport { isPslIdentifier } from '../models/identifiers';\nimport { type FoundModel, findModel, type SqlContract } from '../models/model-lookup';\n\nexport type ComparedModel =\n | { readonly status: 'missing'; readonly expected: BetterAuthModel }\n | { readonly status: 'ambiguous'; readonly expected: BetterAuthModel }\n | {\n readonly status: 'found';\n readonly expected: BetterAuthModel;\n readonly found: FoundModel;\n readonly missingFields: readonly string[];\n };\n\nexport type ContractProblem =\n | {\n readonly kind: 'invalid-name';\n readonly model: string;\n /** The field whose name is not an identifier; absent when it is the model's name. */\n readonly field?: string;\n }\n | {\n readonly kind: 'colliding-model-names';\n /** Physical model names that differ only in the case of the first letter. */\n readonly models: readonly string[];\n }\n | { readonly kind: 'missing-model'; readonly model: string }\n | {\n readonly kind: 'ambiguous-model';\n readonly model: string;\n readonly namespaceIds: readonly string[];\n }\n | { readonly kind: 'missing-field'; readonly model: string; readonly field: string }\n | {\n readonly kind: 'wrong-type';\n readonly model: string;\n readonly field: string;\n /** Better Auth's description of the field, or `undefined` for `id`. */\n readonly attribute: DBFieldAttribute | undefined;\n readonly reference: BetterAuthReference | undefined;\n readonly found: string;\n }\n | {\n readonly kind: 'optional-field-not-nullable';\n readonly model: string;\n readonly field: string;\n readonly attribute: DBFieldAttribute;\n readonly reference: BetterAuthReference | undefined;\n }\n | { readonly kind: 'id-without-default'; readonly model: string }\n | { readonly kind: 'required-field-not-written'; readonly model: string; readonly field: string };\n\nexport interface ContractComparison {\n readonly models: readonly ComparedModel[];\n readonly problems: readonly ContractProblem[];\n readonly idStrategy: IdStrategy;\n readonly namespace: string | undefined;\n /** The namespace a model printed outside a `namespace` block belongs to. */\n readonly defaultNamespace: string;\n /** Contract models that Better Auth's foreign keys reference but that are not among the models it expects, by physical model name. */\n readonly referencedModels: ReadonlyMap<string, FoundModel>;\n /** Physical names of the models whose contract `id` uses the PostgreSQL `uuid` codec, when the id strategy accepts one. */\n readonly uuidKeyedModels: ReadonlySet<string>;\n}\n\nexport interface ComparisonInput {\n readonly contract: SqlContract;\n readonly tables: BetterAuthDBSchema;\n readonly betterAuthOptions: BetterAuthOptions;\n readonly namespace: string | undefined;\n readonly usePlural: boolean;\n}\n\nconst acceptedKindsByIdStrategy: Readonly<Record<IdStrategy, readonly CodecKind[]>> = {\n serial: ['number'],\n uuid: ['string', 'uuid'],\n string: ['string'],\n contract: ['string'],\n};\n\nconst defaultNamespaceByTarget: Readonly<Record<string, string>> = {\n postgres: 'public',\n};\n\nfunction acceptedKinds(attribute: DBFieldAttribute, idStrategy: IdStrategy): readonly CodecKind[] {\n if (isIdReference(attribute)) return acceptedKindsByIdStrategy[idStrategy];\n switch (attribute.type) {\n case 'number':\n return ['number'];\n case 'boolean':\n return ['boolean'];\n case 'date':\n return ['date'];\n case 'string':\n return ['string', 'enum'];\n default:\n return Array.isArray(attribute.type) ? ['string', 'enum'] : ['string'];\n }\n}\n\n/** The description of a contract field whose type Better Auth cannot use, or `undefined` when it can. */\nfunction wrongTypeFound(field: ContractField, accepted: readonly CodecKind[]): string | undefined {\n if (field.type.kind !== 'scalar' || field.many) return describeFieldType(field);\n const kind = codecKind(field.type.codecId);\n return kind === undefined || accepted.includes(kind) ? undefined : describeFieldType(field);\n}\n\nfunction isSqlModelStorage(storage: ContractModelBase['storage']): storage is SqlModelStorage {\n return typeof storage['table'] === 'string' && typeof storage['namespaceId'] === 'string';\n}\n\ninterface ColumnFacts {\n readonly hasDatabaseDefault: boolean;\n readonly hasCreateGenerator: boolean;\n}\n\nfunction columnFacts(contract: SqlContract, found: FoundModel, field: string): ColumnFacts {\n const storage = found.model.storage;\n if (!isSqlModelStorage(storage)) {\n return { hasDatabaseDefault: false, hasCreateGenerator: false };\n }\n const column = storage.fields[field]?.column ?? field;\n const table = resolveStorageTable(contract.storage, storage.table, storage.namespaceId)?.table;\n return {\n hasDatabaseDefault: table?.columns[column]?.default !== undefined,\n hasCreateGenerator: (contract.execution?.mutations.defaults ?? []).some(\n ({ ref, onCreate }) =>\n onCreate !== undefined &&\n ref.namespace === storage.namespaceId &&\n ref.entry === storage.table &&\n ref.field === column,\n ),\n };\n}\n\nfunction compareFoundModel(\n contract: SqlContract,\n expected: BetterAuthModel,\n found: FoundModel,\n idStrategy: IdStrategy,\n problems: ContractProblem[],\n): string[] {\n const fields = found.model.fields;\n const model = found.name;\n const missingFields: string[] = [];\n\n const id = fields['id'];\n if (id === undefined) {\n missingFields.push('id');\n } else {\n const wrong = wrongTypeFound(id, acceptedKindsByIdStrategy[idStrategy]);\n if (wrong !== undefined) {\n problems.push({\n kind: 'wrong-type',\n model,\n field: 'id',\n attribute: undefined,\n reference: undefined,\n found: wrong,\n });\n }\n const facts = columnFacts(contract, found, 'id');\n const betterAuthSendsNoId = idStrategy === 'serial' || idStrategy === 'contract';\n if (betterAuthSendsNoId && !facts.hasDatabaseDefault && !facts.hasCreateGenerator) {\n problems.push({ kind: 'id-without-default', model });\n }\n }\n\n for (const field of expected.fields) {\n const contractField = fields[field.name];\n if (contractField === undefined) {\n missingFields.push(field.name);\n continue;\n }\n const wrong = wrongTypeFound(contractField, acceptedKinds(field.attribute, idStrategy));\n if (wrong !== undefined) {\n problems.push({\n kind: 'wrong-type',\n model,\n field: field.name,\n attribute: field.attribute,\n reference: field.reference,\n found: wrong,\n });\n } else if (mayBeNull(field.attribute) && !contractField.nullable) {\n problems.push({\n kind: 'optional-field-not-nullable',\n model,\n field: field.name,\n attribute: field.attribute,\n reference: field.reference,\n });\n }\n }\n for (const field of missingFields) {\n problems.push({ kind: 'missing-field', model, field });\n }\n\n const written = new Set(['id', ...expected.fields.map((field) => field.name)]);\n for (const [name, field] of Object.entries(fields)) {\n if (written.has(name) || field.nullable) continue;\n const facts = columnFacts(contract, found, name);\n if (!facts.hasDatabaseDefault && !facts.hasCreateGenerator) {\n problems.push({ kind: 'required-field-not-written', model, field: name });\n }\n }\n return missingFields;\n}\n\nfunction hasUuidId(found: FoundModel): boolean {\n const id = found.model.fields['id'];\n return id?.type.kind === 'scalar' && codecKind(id.type.codecId) === 'uuid';\n}\n\nfunction uuidKeyedModelsOf(\n models: readonly ComparedModel[],\n referencedModels: ReadonlyMap<string, FoundModel>,\n): Set<string> {\n const found: [string, FoundModel][] = [\n ...models.flatMap((model): [string, FoundModel][] =>\n model.status === 'found' ? [[model.expected.physicalName, model.found]] : [],\n ),\n ...referencedModels,\n ];\n return new Set(found.filter(([, model]) => hasUuidId(model)).map(([name]) => name));\n}\n\n/** A model or field name that is not a Prisma identifier can be neither matched nor printed, so it is the only problem reported. */\nfunction invalidNameProblems(models: readonly BetterAuthModel[]): ContractProblem[] {\n return models.flatMap((model): ContractProblem[] => [\n ...(isPslIdentifier(model.physicalName)\n ? []\n : [{ kind: 'invalid-name' as const, model: model.physicalName }]),\n ...model.fields\n .filter((field) => !isPslIdentifier(field.name))\n .map((field) => ({\n kind: 'invalid-name' as const,\n model: model.physicalName,\n field: field.name,\n })),\n ]);\n}\n\n/**\n * Compares the contract with the models and fields Better Auth's table description asks for. The contract check and `auth generate` both use it.\n */\nexport function compareContract(input: ComparisonInput): ContractComparison {\n const { contract, betterAuthOptions, namespace } = input;\n const idStrategy = idStrategyOf(betterAuthOptions);\n const defaultNamespace = defaultNamespaceByTarget[contract.target] ?? UNBOUND_DOMAIN_NAMESPACE_ID;\n const expectedModelList = managedModels(input.tables, input);\n const nameProblems: ContractProblem[] = [\n ...invalidNameProblems(expectedModelList),\n ...caseOnlyNameCollisions(betterAuthModels(input.tables, input)).map((models) => ({\n kind: 'colliding-model-names' as const,\n models,\n })),\n ];\n if (nameProblems.length > 0) {\n return {\n models: [],\n problems: nameProblems,\n referencedModels: new Map(),\n uuidKeyedModels: new Set(),\n idStrategy,\n namespace,\n defaultNamespace,\n };\n }\n const problems: ContractProblem[] = [];\n const models: ComparedModel[] = [];\n for (const expected of expectedModelList) {\n const lookup = findModel(contract, expected.physicalName, namespace);\n switch (lookup.kind) {\n case 'missing':\n problems.push({ kind: 'missing-model', model: expected.physicalName });\n models.push({ status: 'missing', expected });\n break;\n case 'ambiguous':\n problems.push({\n kind: 'ambiguous-model',\n model: lookup.name,\n namespaceIds: lookup.namespaceIds,\n });\n models.push({ status: 'ambiguous', expected });\n break;\n case 'found': {\n const missingFields = compareFoundModel(contract, expected, lookup, idStrategy, problems);\n models.push({ status: 'found', expected, found: lookup, missingFields });\n break;\n }\n }\n }\n const expectedNames = new Set(expectedModelList.map((model) => model.physicalName));\n const referencedModels = new Map<string, FoundModel>();\n for (const model of expectedModelList) {\n for (const { reference } of model.fields) {\n if (reference === undefined || expectedNames.has(reference.model)) continue;\n const lookup = findModel(contract, reference.model, namespace);\n if (lookup.kind === 'found') referencedModels.set(reference.model, lookup);\n }\n }\n return {\n models,\n problems,\n referencedModels,\n uuidKeyedModels: acceptedKindsByIdStrategy[idStrategy].includes('uuid')\n ? uuidKeyedModelsOf(models, referencedModels)\n : new Set(),\n idStrategy,\n namespace,\n defaultNamespace,\n };\n}\n","import type { DBFieldAttribute } from '@better-auth/core/db';\nimport {\n type BetterAuthReference,\n type IdStrategy,\n isIdReference,\n} from '../models/better-auth-models';\nimport type { ContractComparison } from './compare';\n\nexport type PslTypeContext = Pick<ContractComparison, 'idStrategy' | 'uuidKeyedModels'>;\n\n/** 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`. */\nexport function pslTypeOf(\n attribute: DBFieldAttribute,\n reference: BetterAuthReference | undefined,\n { idStrategy, uuidKeyedModels }: PslTypeContext,\n): string {\n if (isIdReference(attribute)) {\n if (reference !== undefined && uuidKeyedModels.has(reference.model)) return 'Uuid';\n return idStrategy === 'serial' ? 'Int' : 'String';\n }\n switch (attribute.type) {\n case 'number':\n return attribute.bigint === true ? 'BigInt(as: number)' : 'Int';\n case 'boolean':\n return 'Boolean';\n case 'date':\n return 'DateTime';\n default:\n return 'String';\n }\n}\n\nexport interface IdField {\n readonly name: 'id';\n readonly type: string;\n readonly attributes: string;\n}\n\n/** The `id` field the printed PSL declares, as its columns. */\nexport function idFieldOf(idStrategy: IdStrategy): IdField {\n switch (idStrategy) {\n case 'serial':\n return { name: 'id', type: 'Int', attributes: '@id @default(autoincrement())' };\n case 'contract':\n return { name: 'id', type: 'String', attributes: '@id @onCreate(uuid())' };\n default:\n return { name: 'id', type: 'String', attributes: '@id' };\n }\n}\n\nexport function idLineOf(idStrategy: IdStrategy): string {\n const { name, type, attributes } = idFieldOf(idStrategy);\n return `${name} ${type} ${attributes}`;\n}\n","import type {\n BetterAuthField,\n BetterAuthModel,\n ReferentialAction,\n} from '../models/better-auth-models';\nimport { lowerFirst, upperFirst } from '../models/identifiers';\nimport type { FoundModel } from '../models/model-lookup';\nimport type { ComparedModel, ContractComparison } from './compare';\nimport { idFieldOf, pslTypeOf } from './psl-types';\n\n/** One field line, as its columns: name, type, then attributes when there are any. */\ntype FieldLine = readonly [name: string, type: string, attributes?: string | undefined];\n\nexport interface PrintedBlock {\n /** The model's name: as printed for a missing model, as in the contract for an existing one. */\n readonly modelName: string;\n readonly existing: boolean;\n readonly fieldLines: readonly string[];\n readonly attributeLines: readonly string[];\n}\n\nexport interface PrintedPsl {\n readonly blocks: readonly PrintedBlock[];\n readonly notes: readonly string[];\n readonly text: string;\n}\n\ninterface PrintedModel {\n readonly name: string;\n readonly namespaceId: string;\n readonly existing: boolean;\n readonly taken: Set<string>;\n readonly fields: FieldLine[];\n readonly backRelations: FieldLine[];\n readonly attributes: string[];\n}\n\nconst actionNames: Readonly<Record<ReferentialAction, string>> = {\n cascade: 'Cascade',\n 'no action': 'NoAction',\n restrict: 'Restrict',\n 'set null': 'SetNull',\n 'set default': 'SetDefault',\n};\n\nfunction existingPrintedModel(\n found: FoundModel,\n betterAuthFields: readonly string[],\n): PrintedModel {\n return {\n name: found.name,\n namespaceId: found.namespaceId,\n existing: true,\n taken: new Set([\n ...betterAuthFields,\n ...Object.keys(found.model.fields),\n ...Object.keys(found.model.relations),\n ]),\n fields: [],\n backRelations: [],\n attributes: [],\n };\n}\n\nfunction printedModelFor(\n model: ComparedModel,\n comparison: ContractComparison,\n): PrintedModel | undefined {\n const betterAuthFields = ['id', ...model.expected.fields.map((field) => field.name)];\n switch (model.status) {\n case 'missing':\n return {\n name: upperFirst(model.expected.physicalName),\n namespaceId: comparison.namespace ?? comparison.defaultNamespace,\n existing: false,\n taken: new Set(betterAuthFields),\n fields: [],\n backRelations: [],\n attributes: [],\n };\n case 'found':\n return existingPrintedModel(model.found, betterAuthFields);\n case 'ambiguous':\n return undefined;\n }\n}\n\nfunction typeName(of: PrintedModel, from: PrintedModel): string {\n return of.namespaceId === from.namespaceId ? of.name : `${of.namespaceId}.${of.name}`;\n}\n\nfunction scalarLine(field: BetterAuthField, comparison: ContractComparison): FieldLine {\n const optional = field.attribute.required === false ? '?' : '';\n const type = `${pslTypeOf(field.attribute, field.reference, comparison)}${optional}`;\n return field.attribute.unique === true ? [field.name, type, '@unique'] : [field.name, type];\n}\n\nfunction idLine(comparison: ContractComparison): FieldLine {\n const { name, type, attributes } = idFieldOf(comparison.idStrategy);\n return [name, type, attributes];\n}\n\nfunction freeName(name: string, printed: PrintedModel): string {\n let free = name;\n while (printed.taken.has(free)) free = `${free}_`;\n return free;\n}\n\nfunction relationFieldName(foreignKey: string, holder: PrintedModel): string {\n const stripped = foreignKey.endsWith('Id') ? foreignKey.slice(0, -2) : foreignKey;\n return stripped === '' || stripped === foreignKey || holder.taken.has(stripped)\n ? freeName(`${foreignKey}Relation`, holder)\n : stripped;\n}\n\nfunction foreignKeyCount(expected: BetterAuthModel, referenced: string): number {\n return expected.fields.filter((field) => field.reference?.model === referenced).length;\n}\n\nfunction indexLines(expected: BetterAuthModel): string[] {\n const lines = [\n ...expected.fields\n .filter((field) => field.attribute.index === true && field.attribute.unique !== true)\n .map((field) => `@@index([${field.name}])`),\n ...expected.indexes.map(\n (index) => `${index.unique ? '@@unique' : '@@index'}([${index.fields.join(', ')}])`,\n ),\n ];\n return [...new Set(lines)];\n}\n\nfunction alignedLines(lines: readonly FieldLine[]): string[] {\n const nameWidth = Math.max(0, ...lines.map(([name]) => name.length));\n const typeWidth = Math.max(0, ...lines.map(([, type]) => type.length));\n return lines.map(([name, type, attributes]) =>\n attributes === undefined || attributes === ''\n ? `${name.padEnd(nameWidth)} ${type}`\n : `${name.padEnd(nameWidth)} ${type.padEnd(typeWidth)} ${attributes}`,\n );\n}\n\nfunction blockText(block: PrintedBlock, indent: string): string {\n const body = [...block.fieldLines.map((line) => ` ${line}`)];\n if (block.attributeLines.length > 0) {\n body.push('', ...block.attributeLines.map((line) => ` ${line}`));\n }\n return [`model ${block.modelName} {`, ...body, '}']\n .map((line) => (line === '' ? '' : `${indent}${line}`))\n .join('\\n');\n}\n\n/** PSL text for printed blocks; blocks of missing models go inside a `namespace` block when the adapter's `namespace` option is set. */\nfunction renderBlocks(blocks: readonly PrintedBlock[], namespace: string | undefined): string {\n const chunks: string[] = [];\n let run: PrintedBlock[] = [];\n const flush = () => {\n if (run.length === 0) return;\n const inner = run.map((block) => blockText(block, ' ')).join('\\n\\n');\n chunks.push(`namespace ${namespace} {\\n${inner}\\n}`);\n run = [];\n };\n for (const block of blocks) {\n if (namespace !== undefined && !block.existing) {\n run.push(block);\n continue;\n }\n flush();\n chunks.push(blockText(block, ''));\n }\n flush();\n return chunks.join('\\n\\n');\n}\n\n/**\n * 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.\n */\nexport function printPsl(comparison: ContractComparison): PrintedPsl {\n const printedModels = new Map<string, PrintedModel>();\n for (const model of comparison.models) {\n const printed = printedModelFor(model, comparison);\n if (printed !== undefined) printedModels.set(model.expected.physicalName, printed);\n }\n for (const [physicalName, found] of comparison.referencedModels) {\n printedModels.set(physicalName, existingPrintedModel(found, []));\n }\n const notes: string[] = [];\n\n for (const model of comparison.models) {\n const holder = printedModels.get(model.expected.physicalName);\n if (holder === undefined) continue;\n if (model.status === 'found') {\n for (const name of model.missingFields) {\n const field = model.expected.fields.find((candidate) => candidate.name === name);\n holder.fields.push(\n field === undefined ? idLine(comparison) : scalarLine(field, comparison),\n );\n }\n continue;\n }\n holder.fields.push(idLine(comparison));\n for (const field of model.expected.fields) {\n holder.fields.push(scalarLine(field, comparison));\n const reference = field.reference;\n if (reference === undefined) continue;\n const referenced = printedModels.get(reference.model);\n const optional = field.attribute.required === false;\n\n let action = reference.onDelete;\n if ((action === 'set null' && !optional) || action === 'set default') {\n notes.push(\n `${holder.name}.${field.name}: Better Auth asks for onDelete ${action}, which needs ${action === 'set null' ? 'an optional field' : 'a default'}; NoAction is printed instead`,\n );\n action = 'no action';\n }\n\n const relationName = relationFieldName(field.name, holder);\n holder.taken.add(relationName);\n\n let relationLabel: string | undefined;\n if (referenced !== undefined) {\n const list = field.attribute.unique !== true;\n const base = `${lowerFirst(holder.name)}${list ? 's' : ''}`;\n const named =\n referenced.taken.has(base) || foreignKeyCount(model.expected, reference.model) > 1;\n const backName = named ? freeName(`${base}By${upperFirst(field.name)}`, referenced) : base;\n relationLabel = named ? `\"${holder.name}_${field.name}\"` : undefined;\n referenced.taken.add(backName);\n referenced.backRelations.push([\n backName,\n `${typeName(holder, referenced)}${list ? '[]' : '?'}`,\n relationLabel === undefined ? undefined : `@relation(${relationLabel})`,\n ]);\n }\n\n const referencedType =\n referenced === undefined ? upperFirst(reference.model) : typeName(referenced, holder);\n const relationArguments = [\n ...(relationLabel === undefined ? [] : [relationLabel]),\n `fields: [${field.name}]`,\n `references: [${reference.field}]`,\n `onDelete: ${actionNames[action]}`,\n ].join(', ');\n holder.fields.push([\n relationName,\n `${referencedType}${optional ? '?' : ''}`,\n `@relation(${relationArguments})`,\n ]);\n }\n holder.attributes.push(\n ...indexLines(model.expected),\n `@@map(\"${model.expected.physicalName}\")`,\n );\n }\n\n const blocks: PrintedBlock[] = [];\n for (const printed of printedModels.values()) {\n const lines = [...printed.fields, ...printed.backRelations];\n if (lines.length === 0) continue;\n blocks.push({\n modelName: printed.name,\n existing: printed.existing,\n fieldLines: alignedLines(lines),\n attributeLines: printed.attributes,\n });\n }\n return { blocks, notes, text: renderBlocks(blocks, comparison.namespace) };\n}\n","import { mayBeNull } from '../models/better-auth-models';\nimport {\n caseOnlyNameCollisionMessage,\n invalidFieldNameMessage,\n invalidModelNameMessage,\n} from '../models/identifiers';\nimport { ambiguousModelMessage } from '../models/model-lookup';\nimport type { ContractComparison } from './compare';\nimport { printPsl } from './print-psl';\nimport { idLineOf, pslTypeOf } from './psl-types';\n\nfunction section(title: string, lines: readonly string[]): string[] {\n return lines.length === 0 ? [] : [`${title}:`, '', ...lines.map((line) => ` ${line}`), ''];\n}\n\nfunction changeLines(comparison: ContractComparison): string[] {\n const lines: string[] = [];\n const idLinesPrinted = new Set<string>();\n for (const problem of comparison.problems) {\n switch (problem.kind) {\n case 'ambiguous-model':\n lines.push(ambiguousModelMessage(problem.model, problem.namespaceIds));\n break;\n case 'optional-field-not-nullable':\n lines.push(\n `${problem.model}.${problem.field}: must be \\`${pslTypeOf(problem.attribute, problem.reference, comparison)}?\\`, because Better Auth can write null to it`,\n );\n break;\n case 'id-without-default':\n case 'wrong-type':\n if (problem.kind === 'id-without-default' || problem.attribute === undefined) {\n if (idLinesPrinted.has(problem.model)) break;\n idLinesPrinted.add(problem.model);\n lines.push(`${problem.model}.id: must be \\`${idLineOf(comparison.idStrategy)}\\``);\n break;\n }\n lines.push(\n `${problem.model}.${problem.field}: must be \\`${pslTypeOf(problem.attribute, problem.reference, comparison)}${mayBeNull(problem.attribute) ? '?' : ''}\\` (found ${problem.found})`,\n );\n break;\n }\n }\n return lines;\n}\n\nfunction unwrittenLines(comparison: ContractComparison): string[] {\n return comparison.problems.flatMap((problem) =>\n problem.kind === 'required-field-not-written'\n ? [`${problem.model}.${problem.field}: make it optional or give it a default`]\n : [],\n );\n}\n\n/**\n * The message the contract check and `auth generate` report, or `undefined` when the contract holds everything Better Auth needs.\n */\nexport function contractMessage(comparison: ContractComparison): string | undefined {\n if (comparison.problems.length === 0) return undefined;\n const invalidNames = comparison.problems.flatMap((problem) => {\n if (problem.kind === 'colliding-model-names')\n return [caseOnlyNameCollisionMessage(problem.models)];\n if (problem.kind !== 'invalid-name') return [];\n const message =\n problem.field === undefined\n ? invalidModelNameMessage(problem.model)\n : invalidFieldNameMessage(problem.model, problem.field);\n return message === undefined ? [] : [message];\n });\n if (invalidNames.length > 0) return invalidNames.join('\\n');\n const psl = printPsl(comparison);\n const additions = psl.text === '' ? [] : ['Add to your contract:', '', psl.text, ''];\n const heading =\n additions.length > 0\n ? 'Your Prisma contract is missing models or fields that Better Auth needs.'\n : 'Your Prisma contract does not match what Better Auth needs.';\n return [\n heading,\n '',\n ...additions,\n ...section('Change in your contract', changeLines(comparison)),\n ...section('Fields Better Auth does not write', unwrittenLines(comparison)),\n ...section('Notes', psl.notes),\n 'Then run `prisma contract emit` and update your database.',\n ].join('\\n');\n}\n","import type { BetterAuthOptions } from '@better-auth/core';\nimport * as internal from '@better-auth/core/db/internal';\nimport { BetterAuthError } from '@better-auth/core/error';\nimport { type ComparisonInput, compareContract } from './compare';\nimport { contractMessage } from './message';\n\n/** The error the contract check rejects with and `createSchema` throws. Its `code` is what Better Auth's CLI looks for. */\nexport function contractMismatchError(\n message: string,\n): BetterAuthError & { code: 'SCHEMA_MISMATCH' } {\n return Object.assign(new BetterAuthError(message), { code: 'SCHEMA_MISMATCH' as const });\n}\n\n/** The mismatch error for a contract, or `undefined` when it holds everything Better Auth needs. */\nexport function contractMismatch(input: ComparisonInput): BetterAuthError | undefined {\n const message = contractMessage(compareContract(input));\n return message === undefined ? undefined : contractMismatchError(message);\n}\n\ntype Verdict = { readonly clean: true } | { readonly clean: false; readonly error: unknown };\n\n/**\n * 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.\n */\nexport function createContractCheck(input: () => ComparisonInput): () => Promise<void> | undefined {\n let verdict: Verdict | undefined;\n return () => {\n if (verdict === undefined) {\n try {\n const error = contractMismatch(input());\n verdict = error === undefined ? { clean: true } : { clean: false, error };\n } catch (error) {\n verdict = { clean: false, error };\n }\n }\n return verdict.clean ? undefined : Promise.reject(verdict.error);\n };\n}\n\n/**\n * 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.\n */\nexport function registerContractCheck(\n adapter: object,\n check: () => Promise<void> | undefined,\n betterAuthOptions: BetterAuthOptions,\n): void {\n if (typeof internal.registerSchemaCheck !== 'function') return;\n internal.registerSchemaCheck(adapter, check, {\n runtimeEnabled: betterAuthOptions.advanced?.database?.validateSchema !== false,\n });\n}\n","import type { CleanedWhere } from '@better-auth/core/db/adapter';\nimport { BetterAuthError } from '@better-auth/core/error';\nimport { all, and, or } from '@prisma/orm-family-sql/orm-client';\nimport { codecKind } from './models/codec-kinds';\nimport { describeFieldType } from './models/field-type';\nimport type { FoundModel } from './models/model-lookup';\nimport {\n asCondition,\n type Condition,\n callMethod,\n hasMethod,\n type ModelAccessor,\n property,\n type WhereFunctions,\n type WhereTools,\n} from './orm';\n\n/** 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. */\nfunction scalarCodecIdOf(model: FoundModel, field: string, operator: string): string {\n const type = model.model.fields[field];\n if (type?.type.kind !== 'scalar' || type.many) throw unsupportedError(model, field, operator);\n const kind = codecKind(type.type.codecId);\n if (kind !== undefined && kind !== 'string') throw unsupportedError(model, field, operator);\n return type.type.codecId;\n}\n\nfunction fieldTypeOf(model: FoundModel, field: string): string {\n const contractField = model.model.fields[field];\n return contractField === undefined ? 'unknown type' : describeFieldType(contractField);\n}\n\nexport function unsupportedError(model: FoundModel, field: string, operator: string) {\n return new BetterAuthError(\n `Field \"${model.name}.${field}\" (${fieldTypeOf(model, field)}) does not support ${operator}.`,\n );\n}\n\n/** A field of the callback's model accessor; an unknown field raises the ORM client's own error. */\nexport function fieldOf(accessor: ModelAccessor, field: string): unknown {\n return property(accessor, field);\n}\n\nfunction call(\n field: unknown,\n method: string,\n model: FoundModel,\n name: string,\n operator: string,\n ...args: unknown[]\n): Condition {\n if (!hasMethod(field, method)) throw unsupportedError(model, name, operator);\n return asCondition(callMethod(field, method, ...args));\n}\n\nfunction presentValues(value: CleanedWhere['value']): unknown[] {\n return (Array.isArray(value) ? [...value] : [value]).filter(\n (item) => item !== null && item !== undefined,\n );\n}\n\nfunction allStrings(values: readonly unknown[]): values is string[] {\n return values.length > 0 && values.every((item) => typeof item === 'string');\n}\n\ninterface PatternContext {\n readonly fns: WhereFunctions;\n readonly field: unknown;\n readonly codecId: string;\n}\n\nfunction sensitivePattern(\n { fns, field, codecId }: PatternContext,\n operator: string,\n value: string,\n): Condition {\n const expected = fns.raw`${value}`.returns(codecId);\n switch (operator) {\n case 'starts_with':\n return asCondition(\n fns.eq(fns.raw`substr(${field}, 1, length(${value}))`.returns(codecId), expected),\n );\n case 'ends_with':\n return asCondition(\n fns.eq(\n fns.raw`substr(${field}, length(${field}) - length(${value}) + 1)`.returns(codecId),\n expected,\n ),\n );\n default:\n return asCondition(\n fns.ne(\n fns.raw`replace(${field}, ${value}, '')`.returns(codecId),\n fns.raw`${field}`.returns(codecId),\n ),\n );\n }\n}\n\nfunction insensitivePattern(\n { fns, field, codecId }: PatternContext,\n operator: string,\n value: string,\n): Condition {\n const expected = fns.raw`lower(${value})`.returns(codecId);\n switch (operator) {\n case 'eq':\n return asCondition(fns.eq(fns.raw`lower(${field})`.returns(codecId), expected));\n case 'ne':\n return asCondition(fns.ne(fns.raw`lower(${field})`.returns(codecId), expected));\n case 'starts_with':\n return asCondition(\n fns.eq(\n fns.raw`substr(lower(${field}), 1, length(lower(${value})))`.returns(codecId),\n expected,\n ),\n );\n case 'ends_with':\n return asCondition(\n fns.eq(\n fns.raw`substr(lower(${field}), length(lower(${field})) - length(lower(${value})) + 1)`.returns(\n codecId,\n ),\n expected,\n ),\n );\n default:\n return asCondition(\n fns.ne(\n fns.raw`replace(lower(${field}), lower(${value}), '')`.returns(codecId),\n fns.raw`lower(${field})`.returns(codecId),\n ),\n );\n }\n}\n\nfunction clauseCondition(\n accessor: ModelAccessor,\n { fns }: WhereTools,\n model: FoundModel,\n clause: CleanedWhere,\n): Condition {\n const name = clause.field;\n const field = fieldOf(accessor, name);\n const operator = clause.operator ?? 'eq';\n const value = clause.value;\n const insensitive = clause.mode === 'insensitive';\n const pattern = (): PatternContext => ({\n fns,\n field,\n codecId: scalarCodecIdOf(model, name, operator),\n });\n const method = (methodName: string, ...args: unknown[]) =>\n call(field, methodName, model, name, operator, ...args);\n\n switch (operator) {\n case 'eq':\n case 'ne':\n if (value === null) return method(operator === 'eq' ? 'isNull' : 'isNotNull');\n if (insensitive && typeof value === 'string') {\n return insensitivePattern(pattern(), operator, value);\n }\n return method(operator === 'eq' ? 'eq' : 'neq', value);\n case 'lt':\n case 'lte':\n case 'gt':\n case 'gte':\n return method(operator, value);\n case 'in':\n case 'not_in': {\n const values = presentValues(value);\n const isIn = operator === 'in';\n if (values.length === 0) return isIn ? or() : and();\n if (insensitive && allStrings(values)) {\n const each = values.map((item) => insensitivePattern(pattern(), isIn ? 'eq' : 'ne', item));\n return isIn ? or(...each) : and(...each);\n }\n return method(isIn ? 'in' : 'notIn', values);\n }\n case 'starts_with':\n case 'ends_with':\n case 'contains': {\n const context = pattern();\n const text = String(value);\n if (text === '') return method('isNotNull');\n return insensitive\n ? insensitivePattern(context, operator, text)\n : sensitivePattern(context, operator, text);\n }\n default:\n throw new BetterAuthError(\n `Better Auth filter operator \"${String(operator)}\" is not supported.`,\n );\n }\n}\n\n/** The `where` callback for Better Auth's flat list of clauses: AND clauses, then one OR group. */\nexport function whereFilter(\n model: FoundModel,\n where: readonly CleanedWhere[] | undefined,\n): (accessor: ModelAccessor, tools: WhereTools) => Condition {\n return (accessor, tools) => {\n if (where === undefined || where.length === 0) return all();\n const conditionOf = (clause: CleanedWhere) => clauseCondition(accessor, tools, model, clause);\n const andClauses = where.filter((clause) => clause.connector !== 'OR').map(conditionOf);\n const orClauses = where.filter((clause) => clause.connector === 'OR').map(conditionOf);\n if (orClauses.length === 0) return and(...andClauses);\n if (andClauses.length === 0) return or(...orClauses);\n return and(...andClauses, or(...orClauses));\n };\n}\n","import type { JoinConfig } from '@better-auth/core/db/adapter';\nimport type { ContractRelation } from '@prisma/orm-framework/contract/types';\nimport type { ModelCollections } from './collections';\nimport type { FoundModel } from './models/model-lookup';\nimport type { OrmCollection, Row } from './orm';\n\n/** A joined model served by `include`: the relation's rows move to the join description's key. */\nexport interface IncludedJoin {\n readonly relation: string;\n readonly key: string;\n}\n\nexport interface PlannedJoins {\n readonly collection: OrmCollection;\n readonly included: readonly IncludedJoin[];\n}\n\nfunction sameFields(fields: readonly string[], column: string): boolean {\n return fields.length === 1 && fields[0] === column;\n}\n\nfunction matchingRelation(\n base: FoundModel,\n joined: FoundModel,\n on: { readonly from: string; readonly to: string },\n): [string, ContractRelation] | undefined {\n return Object.entries(base.model.relations).find(\n ([, relation]) =>\n relation.to.model === joined.name &&\n relation.to.namespace === joined.namespaceId &&\n 'on' in relation &&\n sameFields(relation.on.localFields, on.from) &&\n sameFields(relation.on.targetFields, on.to),\n );\n}\n\n/**\n * 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.\n */\nexport function planJoins(\n collection: OrmCollection,\n base: FoundModel,\n join: JoinConfig | undefined,\n collections: ModelCollections,\n debugLog: (...args: unknown[]) => void,\n): PlannedJoins {\n const included: IncludedJoin[] = [];\n let planned = collection;\n for (const [key, config] of Object.entries(join ?? {})) {\n const match = matchingRelation(base, collections.model(key), config.on);\n if (match === undefined) {\n debugLog(\n `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.`,\n );\n continue;\n }\n const [relation, { cardinality }] = match;\n const limit = config.limit;\n planned =\n (cardinality === '1:N' || cardinality === 'N:M') && limit !== undefined\n ? planned.include(relation, (related) => related.limit(limit))\n : planned.include(relation);\n included.push({ relation, key });\n }\n return { collection: planned, included };\n}\n\nexport function moveJoinedRows(row: Row, included: readonly IncludedJoin[]): Row {\n if (included.length === 0) return row;\n const moved: Row = { ...row };\n for (const { relation } of included) delete moved[relation];\n for (const { relation, key } of included) moved[key] = row[relation];\n return moved;\n}\n","import type { BetterAuthOptions } from '@better-auth/core';\nimport { type BetterAuthDBSchema, getAuthTables } from '@better-auth/core/db';\nimport {\n type AdapterFactoryConfig,\n type AdapterFactoryCustomizeAdapterCreator,\n type CleanedWhere,\n type CustomAdapter,\n createAdapterFactory,\n type DBAdapter,\n type DBAdapterSchemaCreation,\n type JoinConfig,\n} from '@better-auth/core/db/adapter';\nimport { BetterAuthError } from '@better-auth/core/error';\nimport { blindCast } from '@prisma/orm-framework/utils/casts';\nimport { createModelCollections, type ModelCollections } from './collections';\nimport {\n contractMismatch,\n contractMismatchError,\n createContractCheck,\n registerContractCheck,\n} from './contract/contract-check';\nimport { fieldOf, unsupportedError, whereFilter } from './filters';\nimport { moveJoinedRows, planJoins } from './joins';\nimport { betterAuthModels, caseOnlyNameCollisions } from './models/better-auth-models';\nimport { assertFieldName, caseOnlyNameCollisionMessage } from './models/identifiers';\nimport type { FoundModel, SqlContract } from './models/model-lookup';\nimport type { PrismaAdapterOptions } from './options';\nimport { callMethod, hasMethod, type OrmCollection, type Row } from './orm';\n\n/**\n * A Prisma 8 Postgres or SQLite client, as `postgres(...)` and `sqlite(...)` return it.\n */\nexport interface PrismaClientLike {\n readonly contract: SqlContract;\n readonly orm: object;\n transaction<R>(fn: (tx: { readonly orm: object }) => PromiseLike<R>): Promise<R>;\n}\n\nconst supportedTargets = ['postgres', 'sqlite'];\n\nfunction assertClient(db: PrismaClientLike, adapterOptions: PrismaAdapterOptions): void {\n const contract: SqlContract | undefined = db.contract;\n if (contract === undefined) {\n throw new BetterAuthError('prismaAdapter needs the Prisma client, not a transaction.');\n }\n if (!supportedTargets.includes(contract.target)) {\n throw new BetterAuthError(\n `@prisma/orm-better-auth supports Postgres and SQLite. This client's database is \"${contract.target}\".`,\n );\n }\n const namespace = adapterOptions.namespace;\n if (namespace !== undefined && !Object.hasOwn(contract.domain.namespaces, namespace)) {\n throw new BetterAuthError(`Namespace \"${namespace}\" is not in your Prisma contract.`);\n }\n}\n\n/** For each physical model name, the fields a read without `select` returns: `id` and every field of Better Auth's table description. */\nfunction defaultSelections(\n schema: BetterAuthDBSchema,\n betterAuthOptions: BetterAuthOptions,\n usePlural: boolean,\n): ReadonlyMap<string, readonly string[]> {\n return new Map(\n betterAuthModels(schema, { betterAuthOptions, usePlural }).map((model) => [\n model.physicalName,\n ['id', ...model.fields.map((field) => field.name)],\n ]),\n );\n}\n\nfunction rowCount(result: Record<string, unknown>): number {\n const count = result['n'];\n if (typeof count !== 'number') throw new BetterAuthError('The count query returned no number.');\n return count;\n}\n\ninterface ModelCall {\n /** The physical model name, which finds the contract model. */\n readonly model: string;\n /** Better Auth's key for the model in its table description, which maps field names. */\n readonly modelKey?: string | undefined;\n}\n\ninterface FilteredCall extends ModelCall {\n readonly where: CleanedWhere[];\n}\n\ninterface ReadCall extends FilteredCall {\n readonly select?: string[] | undefined;\n readonly join?: JoinConfig | undefined;\n}\n\n/** The calls of Better Auth's `CustomAdapter`, with the rows they return typed as rows. */\ninterface RowAdapter {\n create(call: ModelCall & { readonly data: Row }): Promise<Row>;\n findOne(call: ReadCall): Promise<Row | null>;\n findMany(\n call: Omit<ReadCall, 'where'> & {\n readonly where?: CleanedWhere[] | undefined;\n readonly limit: number;\n readonly sortBy?: { readonly field: string; readonly direction: 'asc' | 'desc' } | undefined;\n readonly offset?: number | undefined;\n },\n ): Promise<Row[]>;\n count(call: ModelCall & { readonly where?: CleanedWhere[] | undefined }): Promise<number>;\n update(call: FilteredCall & { readonly update: Row }): Promise<Row | null>;\n updateMany(call: FilteredCall & { readonly update: Row }): Promise<number>;\n delete(call: FilteredCall): Promise<void>;\n deleteMany(call: FilteredCall): Promise<number>;\n createSchema(call: {\n readonly file?: string | undefined;\n readonly tables: BetterAuthDBSchema;\n }): Promise<DBAdapterSchemaCreation>;\n}\n\n/** What one adapter instance computes once and shares with the adapters it builds for transactions. */\ninterface InstanceState {\n readonly collections: ModelCollections;\n /** For each physical model name, the fields a read without `select` returns; computed on the first such read. */\n defaultSelections: ReadonlyMap<string, readonly string[]> | undefined;\n /** The error every call raises when Better Auth's model names collide, `null` when they do not; computed on the first call. */\n nameCollision: Error | null | undefined;\n}\n\ninterface AdapterContext {\n readonly orm: object;\n readonly contract: SqlContract;\n readonly instance: InstanceState;\n readonly adapterOptions: PrismaAdapterOptions;\n}\n\nfunction asCustomAdapter(adapter: RowAdapter): CustomAdapter {\n return blindCast<\n CustomAdapter,\n \"CustomAdapter's methods are generic in the row type the caller expects, which no adapter can know; the rows returned are the model's columns, which is what Better Auth reads\"\n >(adapter);\n}\n\n/** The calls Better Auth's factory makes, over one ORM client root: the client's or a transaction's. */\nfunction customAdapter({\n orm,\n contract,\n instance,\n adapterOptions,\n}: AdapterContext): AdapterFactoryCustomizeAdapterCreator {\n const usePlural = adapterOptions.usePlural ?? false;\n const { collections } = instance;\n return ({ schema, options: betterAuthOptions, getFieldName, debugLog }) => {\n const resolve = (model: string): { found: FoundModel; collection: OrmCollection } => {\n if (instance.nameCollision === undefined) {\n const [collision] = caseOnlyNameCollisions(\n betterAuthModels(schema, { betterAuthOptions, usePlural }),\n );\n instance.nameCollision =\n collision === undefined\n ? null\n : contractMismatchError(caseOnlyNameCollisionMessage(collision));\n }\n if (instance.nameCollision !== null) throw instance.nameCollision;\n const found = collections.model(model);\n return { found, collection: collections.collection(orm, found) };\n };\n\n const assertFieldNames = (model: string, fields: Iterable<string>): void => {\n for (const field of fields) assertFieldName(model, field);\n };\n\n const filterFor = (\n model: string,\n found: FoundModel,\n where: readonly CleanedWhere[] | undefined,\n ) => {\n assertFieldNames(\n model,\n (where ?? []).map((clause) => clause.field),\n );\n return whereFilter(found, where);\n };\n\n const selectionOf = (model: string): readonly string[] => {\n instance.defaultSelections ??= defaultSelections(schema, betterAuthOptions, usePlural);\n const fields = instance.defaultSelections.get(model);\n if (fields === undefined) {\n throw new BetterAuthError(`Better Auth's table description has no model \"${model}\".`);\n }\n return fields;\n };\n\n const selected = (\n { model, modelKey = model }: ModelCall,\n select: readonly string[] | undefined,\n ): readonly string[] => {\n const fields =\n select !== undefined && select.length > 0\n ? select.map((field) => getFieldName({ model: modelKey, field }))\n : selectionOf(model);\n assertFieldNames(model, fields);\n return fields;\n };\n\n const adapter: RowAdapter = {\n async create({ model, data }) {\n assertFieldNames(model, Object.keys(data));\n const { collection } = resolve(model);\n return collection.create(data);\n },\n async findOne({ model, modelKey, where, select, join }) {\n const { found, collection } = resolve(model);\n const filtered = collection\n .where(filterFor(model, found, where))\n .select(...selected({ model, modelKey }, select));\n const joins = planJoins(filtered, found, join, collections, debugLog);\n const row = await joins.collection.first();\n return row === null ? null : moveJoinedRows(row, joins.included);\n },\n async findMany({ model, modelKey, where, limit, select, sortBy, offset, join }) {\n const { found, collection } = resolve(model);\n let query = collection\n .where(filterFor(model, found, where))\n .select(...selected({ model, modelKey }, select));\n if (sortBy !== undefined) {\n const field = getFieldName({ model: modelKey ?? model, field: sortBy.field });\n assertFieldNames(model, [field]);\n const direction: unknown = sortBy.direction;\n if (direction !== 'asc' && direction !== 'desc') {\n throw new BetterAuthError(`Sort direction \"${String(direction)}\" is not supported.`);\n }\n query = query.orderBy((accessor) => {\n const sorted = fieldOf(accessor, field);\n if (!hasMethod(sorted, direction)) throw unsupportedError(found, field, 'sorting');\n return callMethod(sorted, direction);\n });\n }\n query = query.limit(limit);\n if (offset !== undefined) query = query.offset(offset);\n const joins = planJoins(query, found, join, collections, debugLog);\n const rows: Row[] = await joins.collection.all();\n return rows.map((row) => moveJoinedRows(row, joins.included));\n },\n async count({ model, where }) {\n const { found, collection } = resolve(model);\n return rowCount(\n await collection\n .where(filterFor(model, found, where))\n .aggregate((aggregates) => ({ n: aggregates.count() })),\n );\n },\n async update({ model, where, update }) {\n assertFieldNames(model, Object.keys(update));\n const { found, collection } = resolve(model);\n return collection.where(filterFor(model, found, where)).update(update);\n },\n async updateMany({ model, where, update }) {\n assertFieldNames(model, Object.keys(update));\n const { found, collection } = resolve(model);\n return collection.where(filterFor(model, found, where)).updateAndCount(update);\n },\n async delete({ model, where }) {\n const { found, collection } = resolve(model);\n await collection.where(filterFor(model, found, where)).deleteAndCount();\n },\n async deleteMany({ model, where }) {\n const { found, collection } = resolve(model);\n return collection.where(filterFor(model, found, where)).deleteAndCount();\n },\n async createSchema({ file, tables }) {\n const error = contractMismatch({\n contract,\n tables,\n betterAuthOptions,\n namespace: adapterOptions.namespace,\n usePlural,\n });\n if (error !== undefined) throw error;\n return { code: '', path: file ?? 'prisma/contract.prisma' };\n },\n };\n return asCustomAdapter(adapter);\n };\n}\n\nfunction factoryConfig(\n adapterOptions: PrismaAdapterOptions,\n transaction: AdapterFactoryConfig['transaction'],\n): AdapterFactoryConfig {\n return {\n adapterId: 'prisma-8',\n adapterName: 'Prisma 8',\n usePlural: adapterOptions.usePlural ?? false,\n debugLogs: adapterOptions.debugLogs ?? false,\n supportsDates: true,\n supportsBooleans: true,\n supportsNumericIds: true,\n supportsJSON: false,\n supportsArrays: false,\n supportsUUIDs: false,\n transaction,\n };\n}\n\n/**\n * A Better Auth database adapter over a Prisma 8 Postgres or SQLite client.\n *\n * @example\n * ```ts\n * export const auth = betterAuth({ database: prismaAdapter(db) });\n * ```\n */\nexport function prismaAdapter(\n db: PrismaClientLike,\n adapterOptions: PrismaAdapterOptions = {},\n): (betterAuthOptions: BetterAuthOptions) => DBAdapter<BetterAuthOptions> {\n assertClient(db, adapterOptions);\n return (betterAuthOptions) => {\n const context: AdapterContext = {\n orm: db.orm,\n contract: db.contract,\n instance: {\n collections: createModelCollections(db.contract, adapterOptions.namespace),\n defaultSelections: undefined,\n nameCollision: undefined,\n },\n adapterOptions,\n };\n const transaction: AdapterFactoryConfig['transaction'] =\n adapterOptions.transaction === true\n ? (callback) =>\n db.transaction((tx) =>\n callback(\n createAdapterFactory({\n config: factoryConfig(adapterOptions, false),\n adapter: customAdapter({ ...context, orm: tx.orm }),\n })(betterAuthOptions),\n ),\n )\n : false;\n const adapter = createAdapterFactory({\n config: factoryConfig(adapterOptions, transaction),\n adapter: customAdapter(context),\n })(betterAuthOptions);\n registerContractCheck(\n adapter,\n createContractCheck(() => ({\n contract: db.contract,\n tables: getAuthTables(betterAuthOptions),\n betterAuthOptions,\n namespace: adapterOptions.namespace,\n usePlural: adapterOptions.usePlural ?? false,\n })),\n betterAuthOptions,\n );\n return adapter;\n };\n}\n"],"mappings":";;;;;;;;;AAEA,MAAM,gBAAgB;AAEtB,SAAgB,gBAAgB,MAAuB;CACrD,OAAO,cAAc,KAAK,IAAI;AAChC;;AAGA,SAAgB,wBAAwB,MAAkC;CACxE,IAAI,gBAAgB,IAAI,GAAG,OAAO,KAAA;CAClC,OAAO,6BAA6B,KAAK;AAC3C;;AAGA,SAAgB,wBAAwB,OAAe,OAAmC;CACxF,IAAI,gB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,MAAM,UAAU;IACnC,MAAM,QAAQ,iBAAiB;KAC7B;KACA;KACA;KACA,WAAW,eAAe;KAC1B;IACF,CAAC;IACD,IAAI,UAAU,KAAA,GAAW,MAAM;IAC/B,OAAO;KAAE,MAAM;KAAI,MAAM,QAAQ;IAAyB;GAC5D;EAE2B,CAAC;CAChC;AACF;AAEA,SAAS,cACP,gBACA,aACsB;CACtB,OAAO;EACL,WAAW;EACX,aAAa;EACb,WAAW,eAAe,aAAa;EACvC,WAAW,eAAe,aAAa;EACvC,eAAe;EACf,kBAAkB;EAClB,oBAAoB;EACpB,cAAc;EACd,gBAAgB;EAChB,eAAe;EACf;CACF;AACF;;;;;;;;;AAUA,SAAgB,cACd,IACA,iBAAuC,CAAC,GACgC;CACxE,aAAa,IAAI,cAAc;CAC/B,QAAQ,sBAAsB;EAC5B,MAAM,UAA0B;GAC9B,KAAK,GAAG;GACR,UAAU,GAAG;GACb,UAAU;IACR,aAAa,uBAAuB,GAAG,UAAU,eAAe,SAAS;IACzE,mBAAmB,KAAA;IACnB,eAAe,KAAA;GACjB;GACA;EACF;EAaA,MAAM,UAAU,qBAAqB;GACnC,QAAQ,cAAc,gBAZtB,eAAe,gBAAgB,QAC1B,aACC,GAAG,aAAa,OACd,SACE,qBAAqB;IACnB,QAAQ,cAAc,gBAAgB,KAAK;IAC3C,SAAS,cAAc;KAAE,GAAG;KAAS,KAAK,GAAG;IAAI,CAAC;GACpD,CAAC,CAAC,CAAC,iBAAiB,CACtB,CACF,IACF,KAE6C;GACjD,SAAS,cAAc,OAAO;EAChC,CAAC,CAAC,CAAC,iBAAiB;EACpB,sBACE,SACA,2BAA2B;GACzB,UAAU,GAAG;GACb,QAAQ,cAAc,iBAAiB;GACvC;GACA,WAAW,eAAe;GAC1B,WAAW,eAAe,aAAa;EACzC,EAAE,GACF,iBACF;EACA,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/orm.ts","../src/collections.ts","../src/filters.ts","../src/joins.ts","../src/adapter.ts"],"sourcesContent":["import type { and } from '@prisma/orm-family-sql/orm-client';\nimport { blindCast } from '@prisma/orm-framework/utils/casts';\n\n/** A filter the ORM client's `and`, `or` and `where` accept. */\nexport type Condition = Parameters<typeof and>[number];\n\nexport type Row = Record<string, unknown>;\n\n/** A raw SQL expression built with `fns.raw`, before its codec is named. */\nexport interface RawExpression {\n returns(codecId: string): unknown;\n}\n\nexport interface WhereFunctions {\n raw(strings: TemplateStringsArray, ...values: unknown[]): RawExpression;\n eq(left: unknown, right: unknown): unknown;\n ne(left: unknown, right: unknown): unknown;\n}\n\nexport interface WhereTools {\n readonly fns: WhereFunctions;\n}\n\n/** The model accessor a `where` or `orderBy` callback receives. Its properties are the model's fields. */\nexport type ModelAccessor = object;\n\n/**\n * The part of an ORM client collection the adapter calls. The adapter reaches collections by run-time model name, so their contract types are not known here.\n */\nexport interface OrmCollection {\n where(filter: (model: ModelAccessor, tools: WhereTools) => Condition): OrmCollection;\n select(...fields: string[]): OrmCollection;\n orderBy(selector: (model: ModelAccessor) => unknown): OrmCollection;\n limit(count: number): OrmCollection;\n offset(count: number): OrmCollection;\n include(relation: string, refine?: (related: OrmCollection) => OrmCollection): OrmCollection;\n first(): Promise<Row | null>;\n all(): PromiseLike<Row[]>;\n aggregate(\n build: (aggregates: { count(): unknown }) => Record<string, unknown>,\n ): Promise<Record<string, unknown>>;\n create(data: Row): Promise<Row>;\n update(data: Row): Promise<Row | null>;\n updateAndCount(data: Row): Promise<number>;\n deleteAndCount(): Promise<number>;\n}\n\nconst collectionMethods = [\n 'where',\n 'select',\n 'orderBy',\n 'limit',\n 'offset',\n 'include',\n 'first',\n 'all',\n 'aggregate',\n 'create',\n 'update',\n 'updateAndCount',\n 'deleteAndCount',\n] as const satisfies readonly (keyof OrmCollection)[];\n\nexport function isOrmCollection(value: unknown): value is OrmCollection {\n return (\n typeof value === 'object' &&\n value !== null &&\n collectionMethods.every((method) => typeof Reflect.get(value, method) === 'function')\n );\n}\n\n/** A property of an ORM client proxy, read by run-time name. */\nexport function property(target: unknown, name: string): unknown {\n return typeof target === 'object' && target !== null ? Reflect.get(target, name) : undefined;\n}\n\n/** Calls a method of an ORM client object by run-time name, or returns `undefined` when it has none. */\nexport function callMethod(target: unknown, name: string, ...args: unknown[]): unknown {\n const method = property(target, name);\n if (typeof method !== 'function') return undefined;\n return Reflect.apply(method, target, args);\n}\n\nexport function hasMethod(target: unknown, name: string): boolean {\n return typeof property(target, name) === 'function';\n}\n\n/** A filter built by calling the ORM client's field and `fns` methods by run-time name. */\nexport function asCondition(value: unknown): Condition {\n return blindCast<\n Condition,\n 'field and fns methods are called by run-time name, so their filter results arrive untyped; each comes from an ORM client method that returns a filter'\n >(value);\n}\n","import { BetterAuthError } from '@better-auth/core/error';\nimport { UNBOUND_DOMAIN_NAMESPACE_ID } from '@prisma/orm-framework/contract/default-namespace';\nimport { assertModelName } from './models/identifiers';\nimport {\n ambiguousModelMessage,\n type FoundModel,\n findModel,\n missingModelMessage,\n type SqlContract,\n} from './models/model-lookup';\nimport { isOrmCollection, type OrmCollection, property } from './orm';\n\nexport interface ModelCollections {\n /** The contract model for a Better Auth physical model name; raises a `BetterAuthError` when the name is not an identifier, or when no model or more than one has it. */\n model(physicalName: string): FoundModel;\n /** The model's collection on an ORM client root: the client's, or a transaction's. */\n collection(orm: object, model: FoundModel): OrmCollection;\n}\n\n/** Finds each model once per adapter instance, and its collection on the ORM client root a call uses. */\nexport function createModelCollections(\n contract: SqlContract,\n namespace: string | undefined,\n): ModelCollections {\n const found = new Map<string, FoundModel>();\n const namespaceIds = Object.keys(contract.domain.namespaces);\n const flat = namespaceIds.length === 1 && namespaceIds[0] === UNBOUND_DOMAIN_NAMESPACE_ID;\n return {\n model(physicalName) {\n const known = found.get(physicalName);\n if (known !== undefined) return known;\n assertModelName(physicalName);\n const lookup = findModel(contract, physicalName, namespace);\n if (lookup.kind === 'ambiguous') {\n throw new BetterAuthError(ambiguousModelMessage(lookup.name, lookup.namespaceIds));\n }\n if (lookup.kind === 'missing') throw new BetterAuthError(missingModelMessage(physicalName));\n found.set(physicalName, lookup);\n return lookup;\n },\n collection(orm, model) {\n const facet = flat ? orm : property(orm, model.namespaceId);\n const collection = property(facet, model.name);\n if (!isOrmCollection(collection)) {\n throw new BetterAuthError(missingModelMessage(model.name));\n }\n return collection;\n },\n };\n}\n","import type { CleanedWhere } from '@better-auth/core/db/adapter';\nimport { BetterAuthError } from '@better-auth/core/error';\nimport { all, and, or } from '@prisma/orm-family-sql/orm-client';\nimport { codecKind } from './models/codec-kinds';\nimport { describeFieldType } from './models/field-type';\nimport type { FoundModel } from './models/model-lookup';\nimport {\n asCondition,\n type Condition,\n callMethod,\n hasMethod,\n type ModelAccessor,\n property,\n type WhereFunctions,\n type WhereTools,\n} from './orm';\n\n/** 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. */\nfunction scalarCodecIdOf(model: FoundModel, field: string, operator: string): string {\n const type = model.model.fields[field];\n if (type?.type.kind !== 'scalar' || type.many) throw unsupportedError(model, field, operator);\n const kind = codecKind(type.type.codecId);\n if (kind !== undefined && kind !== 'string') throw unsupportedError(model, field, operator);\n return type.type.codecId;\n}\n\nfunction fieldTypeOf(model: FoundModel, field: string): string {\n const contractField = model.model.fields[field];\n return contractField === undefined ? 'unknown type' : describeFieldType(contractField);\n}\n\nexport function unsupportedError(model: FoundModel, field: string, operator: string) {\n return new BetterAuthError(\n `Field \"${model.name}.${field}\" (${fieldTypeOf(model, field)}) does not support ${operator}.`,\n );\n}\n\n/** A field of the callback's model accessor; an unknown field raises the ORM client's own error. */\nexport function fieldOf(accessor: ModelAccessor, field: string): unknown {\n return property(accessor, field);\n}\n\nfunction call(\n field: unknown,\n method: string,\n model: FoundModel,\n name: string,\n operator: string,\n ...args: unknown[]\n): Condition {\n if (!hasMethod(field, method)) throw unsupportedError(model, name, operator);\n return asCondition(callMethod(field, method, ...args));\n}\n\nfunction presentValues(value: CleanedWhere['value']): unknown[] {\n return (Array.isArray(value) ? [...value] : [value]).filter(\n (item) => item !== null && item !== undefined,\n );\n}\n\nfunction allStrings(values: readonly unknown[]): values is string[] {\n return values.length > 0 && values.every((item) => typeof item === 'string');\n}\n\ninterface PatternContext {\n readonly fns: WhereFunctions;\n readonly field: unknown;\n readonly codecId: string;\n}\n\nfunction sensitivePattern(\n { fns, field, codecId }: PatternContext,\n operator: string,\n value: string,\n): Condition {\n const expected = fns.raw`${value}`.returns(codecId);\n switch (operator) {\n case 'starts_with':\n return asCondition(\n fns.eq(fns.raw`substr(${field}, 1, length(${value}))`.returns(codecId), expected),\n );\n case 'ends_with':\n return asCondition(\n fns.eq(\n fns.raw`substr(${field}, length(${field}) - length(${value}) + 1)`.returns(codecId),\n expected,\n ),\n );\n default:\n return asCondition(\n fns.ne(\n fns.raw`replace(${field}, ${value}, '')`.returns(codecId),\n fns.raw`${field}`.returns(codecId),\n ),\n );\n }\n}\n\nfunction insensitivePattern(\n { fns, field, codecId }: PatternContext,\n operator: string,\n value: string,\n): Condition {\n const expected = fns.raw`lower(${value})`.returns(codecId);\n switch (operator) {\n case 'eq':\n return asCondition(fns.eq(fns.raw`lower(${field})`.returns(codecId), expected));\n case 'ne':\n return asCondition(fns.ne(fns.raw`lower(${field})`.returns(codecId), expected));\n case 'starts_with':\n return asCondition(\n fns.eq(\n fns.raw`substr(lower(${field}), 1, length(lower(${value})))`.returns(codecId),\n expected,\n ),\n );\n case 'ends_with':\n return asCondition(\n fns.eq(\n fns.raw`substr(lower(${field}), length(lower(${field})) - length(lower(${value})) + 1)`.returns(\n codecId,\n ),\n expected,\n ),\n );\n default:\n return asCondition(\n fns.ne(\n fns.raw`replace(lower(${field}), lower(${value}), '')`.returns(codecId),\n fns.raw`lower(${field})`.returns(codecId),\n ),\n );\n }\n}\n\nfunction clauseCondition(\n accessor: ModelAccessor,\n { fns }: WhereTools,\n model: FoundModel,\n clause: CleanedWhere,\n): Condition {\n const name = clause.field;\n const field = fieldOf(accessor, name);\n const operator = clause.operator ?? 'eq';\n const value = clause.value;\n const insensitive = clause.mode === 'insensitive';\n const pattern = (): PatternContext => ({\n fns,\n field,\n codecId: scalarCodecIdOf(model, name, operator),\n });\n const method = (methodName: string, ...args: unknown[]) =>\n call(field, methodName, model, name, operator, ...args);\n\n switch (operator) {\n case 'eq':\n case 'ne':\n if (value === null) return method(operator === 'eq' ? 'isNull' : 'isNotNull');\n if (insensitive && typeof value === 'string') {\n return insensitivePattern(pattern(), operator, value);\n }\n return method(operator === 'eq' ? 'eq' : 'neq', value);\n case 'lt':\n case 'lte':\n case 'gt':\n case 'gte':\n return method(operator, value);\n case 'in':\n case 'not_in': {\n const values = presentValues(value);\n const isIn = operator === 'in';\n if (values.length === 0) return isIn ? or() : and();\n if (insensitive && allStrings(values)) {\n const each = values.map((item) => insensitivePattern(pattern(), isIn ? 'eq' : 'ne', item));\n return isIn ? or(...each) : and(...each);\n }\n return method(isIn ? 'in' : 'notIn', values);\n }\n case 'starts_with':\n case 'ends_with':\n case 'contains': {\n const context = pattern();\n const text = String(value);\n if (text === '') return method('isNotNull');\n return insensitive\n ? insensitivePattern(context, operator, text)\n : sensitivePattern(context, operator, text);\n }\n default:\n throw new BetterAuthError(\n `Better Auth filter operator \"${String(operator)}\" is not supported.`,\n );\n }\n}\n\n/** The `where` callback for Better Auth's flat list of clauses: AND clauses, then one OR group. */\nexport function whereFilter(\n model: FoundModel,\n where: readonly CleanedWhere[] | undefined,\n): (accessor: ModelAccessor, tools: WhereTools) => Condition {\n return (accessor, tools) => {\n if (where === undefined || where.length === 0) return all();\n const conditionOf = (clause: CleanedWhere) => clauseCondition(accessor, tools, model, clause);\n const andClauses = where.filter((clause) => clause.connector !== 'OR').map(conditionOf);\n const orClauses = where.filter((clause) => clause.connector === 'OR').map(conditionOf);\n if (orClauses.length === 0) return and(...andClauses);\n if (andClauses.length === 0) return or(...orClauses);\n return and(...andClauses, or(...orClauses));\n };\n}\n","import type { JoinConfig } from '@better-auth/core/db/adapter';\nimport type { ContractRelation } from '@prisma/orm-framework/contract/types';\nimport type { ModelCollections } from './collections';\nimport type { FoundModel } from './models/model-lookup';\nimport type { OrmCollection, Row } from './orm';\n\n/** A joined model served by `include`: the relation's rows move to the join description's key. */\nexport interface IncludedJoin {\n readonly relation: string;\n readonly key: string;\n}\n\nexport interface PlannedJoins {\n readonly collection: OrmCollection;\n readonly included: readonly IncludedJoin[];\n}\n\nfunction sameFields(fields: readonly string[], column: string): boolean {\n return fields.length === 1 && fields[0] === column;\n}\n\nfunction matchingRelation(\n base: FoundModel,\n joined: FoundModel,\n on: { readonly from: string; readonly to: string },\n): [string, ContractRelation] | undefined {\n return Object.entries(base.model.relations).find(\n ([, relation]) =>\n relation.to.model === joined.name &&\n relation.to.namespace === joined.namespaceId &&\n 'on' in relation &&\n sameFields(relation.on.localFields, on.from) &&\n sameFields(relation.on.targetFields, on.to),\n );\n}\n\n/**\n * 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.\n */\nexport function planJoins(\n collection: OrmCollection,\n base: FoundModel,\n join: JoinConfig | undefined,\n collections: ModelCollections,\n debugLog: (...args: unknown[]) => void,\n): PlannedJoins {\n const included: IncludedJoin[] = [];\n let planned = collection;\n for (const [key, config] of Object.entries(join ?? {})) {\n const match = matchingRelation(base, collections.model(key), config.on);\n if (match === undefined) {\n debugLog(\n `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.`,\n );\n continue;\n }\n const [relation, { cardinality }] = match;\n const limit = config.limit;\n planned =\n (cardinality === '1:N' || cardinality === 'N:M') && limit !== undefined\n ? planned.include(relation, (related) => related.limit(limit))\n : planned.include(relation);\n included.push({ relation, key });\n }\n return { collection: planned, included };\n}\n\nexport function moveJoinedRows(row: Row, included: readonly IncludedJoin[]): Row {\n if (included.length === 0) return row;\n const moved: Row = { ...row };\n for (const { relation } of included) delete moved[relation];\n for (const { relation, key } of included) moved[key] = row[relation];\n return moved;\n}\n","import type { BetterAuthOptions } from '@better-auth/core';\nimport { type BetterAuthDBSchema, getAuthTables } from '@better-auth/core/db';\nimport {\n type AdapterFactoryConfig,\n type AdapterFactoryCustomizeAdapterCreator,\n type CleanedWhere,\n type CustomAdapter,\n createAdapterFactory,\n type DBAdapter,\n type DBAdapterSchemaCreation,\n type JoinConfig,\n} from '@better-auth/core/db/adapter';\nimport { BetterAuthError } from '@better-auth/core/error';\nimport { blindCast } from '@prisma/orm-framework/utils/casts';\nimport { createModelCollections, type ModelCollections } from './collections';\nimport { compareContract } from './contract/compare';\nimport {\n contractMismatchError,\n createContractCheck,\n registerContractCheck,\n} from './contract/contract-check';\nimport { fieldOf, unsupportedError, whereFilter } from './filters';\nimport { moveJoinedRows, planJoins } from './joins';\nimport { betterAuthModels, caseOnlyNameCollisions } from './models/better-auth-models';\nimport { assertFieldName, caseOnlyNameCollisionMessage } from './models/identifiers';\nimport type { FoundModel, SqlContract } from './models/model-lookup';\nimport type { PrismaAdapterOptions } from './options';\nimport { callMethod, hasMethod, type OrmCollection, type Row } from './orm';\n\n/**\n * A Prisma 8 Postgres or SQLite client, as `postgres(...)` and `sqlite(...)` return it.\n */\nexport interface PrismaClientLike {\n readonly contract: SqlContract;\n readonly orm: object;\n transaction<R>(fn: (tx: { readonly orm: object }) => PromiseLike<R>): Promise<R>;\n}\n\nconst supportedTargets = ['postgres', 'sqlite'];\n\nfunction assertClient(db: PrismaClientLike, adapterOptions: PrismaAdapterOptions): void {\n const contract: SqlContract | undefined = db.contract;\n if (contract === undefined) {\n throw new BetterAuthError('prismaAdapter needs the Prisma client, not a transaction.');\n }\n if (!supportedTargets.includes(contract.target)) {\n throw new BetterAuthError(\n `@prisma/orm-better-auth supports Postgres and SQLite. This client's database is \"${contract.target}\".`,\n );\n }\n const namespace = adapterOptions.namespace;\n if (namespace !== undefined && !Object.hasOwn(contract.domain.namespaces, namespace)) {\n throw new BetterAuthError(`Namespace \"${namespace}\" is not in your Prisma contract.`);\n }\n}\n\n/** For each physical model name, the fields a read without `select` returns: `id` and every field of Better Auth's table description. */\nfunction defaultSelections(\n schema: BetterAuthDBSchema,\n betterAuthOptions: BetterAuthOptions,\n usePlural: boolean,\n): ReadonlyMap<string, readonly string[]> {\n return new Map(\n betterAuthModels(schema, { betterAuthOptions, usePlural }).map((model) => [\n model.physicalName,\n ['id', ...model.fields.map((field) => field.name)],\n ]),\n );\n}\n\nfunction rowCount(result: Record<string, unknown>): number {\n const count = result['n'];\n if (typeof count !== 'number') throw new BetterAuthError('The count query returned no number.');\n return count;\n}\n\ninterface ModelCall {\n /** The physical model name, which finds the contract model. */\n readonly model: string;\n /** Better Auth's key for the model in its table description, which maps field names. */\n readonly modelKey?: string | undefined;\n}\n\ninterface FilteredCall extends ModelCall {\n readonly where: CleanedWhere[];\n}\n\ninterface ReadCall extends FilteredCall {\n readonly select?: string[] | undefined;\n readonly join?: JoinConfig | undefined;\n}\n\n/** The calls of Better Auth's `CustomAdapter`, with the rows they return typed as rows. */\ninterface RowAdapter {\n create(call: ModelCall & { readonly data: Row }): Promise<Row>;\n findOne(call: ReadCall): Promise<Row | null>;\n findMany(\n call: Omit<ReadCall, 'where'> & {\n readonly where?: CleanedWhere[] | undefined;\n readonly limit: number;\n readonly sortBy?: { readonly field: string; readonly direction: 'asc' | 'desc' } | undefined;\n readonly offset?: number | undefined;\n },\n ): Promise<Row[]>;\n count(call: ModelCall & { readonly where?: CleanedWhere[] | undefined }): Promise<number>;\n update(call: FilteredCall & { readonly update: Row }): Promise<Row | null>;\n updateMany(call: FilteredCall & { readonly update: Row }): Promise<number>;\n delete(call: FilteredCall): Promise<void>;\n deleteMany(call: FilteredCall): Promise<number>;\n createSchema(call: {\n readonly file?: string | undefined;\n readonly tables: BetterAuthDBSchema;\n }): Promise<DBAdapterSchemaCreation>;\n}\n\n/** What one adapter instance computes once and shares with the adapters it builds for transactions. */\ninterface InstanceState {\n readonly collections: ModelCollections;\n /** For each physical model name, the fields a read without `select` returns; computed on the first such read. */\n defaultSelections: ReadonlyMap<string, readonly string[]> | undefined;\n /** The error every call raises when Better Auth's model names collide, `null` when they do not; computed on the first call. */\n nameCollision: Error | null | undefined;\n}\n\ninterface AdapterContext {\n readonly orm: object;\n readonly contract: SqlContract;\n readonly instance: InstanceState;\n readonly adapterOptions: PrismaAdapterOptions;\n}\n\nfunction asCustomAdapter(adapter: RowAdapter): CustomAdapter {\n return blindCast<\n CustomAdapter,\n \"CustomAdapter's methods are generic in the row type the caller expects, which no adapter can know; the rows returned are the model's columns, which is what Better Auth reads\"\n >(adapter);\n}\n\n/** The calls Better Auth's factory makes, over one ORM client root: the client's or a transaction's. */\nfunction customAdapter({\n orm,\n contract,\n instance,\n adapterOptions,\n}: AdapterContext): AdapterFactoryCustomizeAdapterCreator {\n const usePlural = adapterOptions.usePlural ?? false;\n const { collections } = instance;\n return ({ schema, options: betterAuthOptions, getFieldName, debugLog }) => {\n const resolve = (model: string): { found: FoundModel; collection: OrmCollection } => {\n if (instance.nameCollision === undefined) {\n const [collision] = caseOnlyNameCollisions(\n betterAuthModels(schema, { betterAuthOptions, usePlural }),\n );\n instance.nameCollision =\n collision === undefined\n ? null\n : contractMismatchError(caseOnlyNameCollisionMessage(collision));\n }\n if (instance.nameCollision !== null) throw instance.nameCollision;\n const found = collections.model(model);\n return { found, collection: collections.collection(orm, found) };\n };\n\n const assertFieldNames = (model: string, fields: Iterable<string>): void => {\n for (const field of fields) assertFieldName(model, field);\n };\n\n const filterFor = (\n model: string,\n found: FoundModel,\n where: readonly CleanedWhere[] | undefined,\n ) => {\n assertFieldNames(\n model,\n (where ?? []).map((clause) => clause.field),\n );\n return whereFilter(found, where);\n };\n\n const selectionOf = (model: string): readonly string[] => {\n instance.defaultSelections ??= defaultSelections(schema, betterAuthOptions, usePlural);\n const fields = instance.defaultSelections.get(model);\n if (fields === undefined) {\n throw new BetterAuthError(`Better Auth's table description has no model \"${model}\".`);\n }\n return fields;\n };\n\n const selected = (\n { model, modelKey = model }: ModelCall,\n select: readonly string[] | undefined,\n ): readonly string[] => {\n const fields =\n select !== undefined && select.length > 0\n ? select.map((field) => getFieldName({ model: modelKey, field }))\n : selectionOf(model);\n assertFieldNames(model, fields);\n return fields;\n };\n\n const adapter: RowAdapter = {\n async create({ model, data }) {\n assertFieldNames(model, Object.keys(data));\n const { collection } = resolve(model);\n return collection.create(data);\n },\n async findOne({ model, modelKey, where, select, join }) {\n const { found, collection } = resolve(model);\n const filtered = collection\n .where(filterFor(model, found, where))\n .select(...selected({ model, modelKey }, select));\n const joins = planJoins(filtered, found, join, collections, debugLog);\n const row = await joins.collection.first();\n return row === null ? null : moveJoinedRows(row, joins.included);\n },\n async findMany({ model, modelKey, where, limit, select, sortBy, offset, join }) {\n const { found, collection } = resolve(model);\n let query = collection\n .where(filterFor(model, found, where))\n .select(...selected({ model, modelKey }, select));\n if (sortBy !== undefined) {\n const field = getFieldName({ model: modelKey ?? model, field: sortBy.field });\n assertFieldNames(model, [field]);\n const direction: unknown = sortBy.direction;\n if (direction !== 'asc' && direction !== 'desc') {\n throw new BetterAuthError(`Sort direction \"${String(direction)}\" is not supported.`);\n }\n query = query.orderBy((accessor) => {\n const sorted = fieldOf(accessor, field);\n if (!hasMethod(sorted, direction)) throw unsupportedError(found, field, 'sorting');\n return callMethod(sorted, direction);\n });\n }\n query = query.limit(limit);\n if (offset !== undefined) query = query.offset(offset);\n const joins = planJoins(query, found, join, collections, debugLog);\n const rows: Row[] = await joins.collection.all();\n return rows.map((row) => moveJoinedRows(row, joins.included));\n },\n async count({ model, where }) {\n const { found, collection } = resolve(model);\n return rowCount(\n await collection\n .where(filterFor(model, found, where))\n .aggregate((aggregates) => ({ n: aggregates.count() })),\n );\n },\n async update({ model, where, update }) {\n assertFieldNames(model, Object.keys(update));\n const { found, collection } = resolve(model);\n return collection.where(filterFor(model, found, where)).update(update);\n },\n async updateMany({ model, where, update }) {\n assertFieldNames(model, Object.keys(update));\n const { found, collection } = resolve(model);\n return collection.where(filterFor(model, found, where)).updateAndCount(update);\n },\n async delete({ model, where }) {\n const { found, collection } = resolve(model);\n await collection.where(filterFor(model, found, where)).deleteAndCount();\n },\n async deleteMany({ model, where }) {\n const { found, collection } = resolve(model);\n return collection.where(filterFor(model, found, where)).deleteAndCount();\n },\n async createSchema({ file, tables }) {\n const comparison = compareContract({\n contract,\n tables,\n betterAuthOptions,\n namespace: adapterOptions.namespace,\n usePlural,\n });\n if (comparison.problems.length === 0) {\n return { code: '', path: file ?? 'prisma/contract.prisma' };\n }\n const { editedContractSource } = await import('./generate/edited-contract-source');\n return editedContractSource(file, comparison);\n },\n };\n return asCustomAdapter(adapter);\n };\n}\n\nfunction factoryConfig(\n adapterOptions: PrismaAdapterOptions,\n transaction: AdapterFactoryConfig['transaction'],\n): AdapterFactoryConfig {\n return {\n adapterId: 'prisma-8',\n adapterName: 'Prisma 8',\n usePlural: adapterOptions.usePlural ?? false,\n debugLogs: adapterOptions.debugLogs ?? false,\n supportsDates: true,\n supportsBooleans: true,\n supportsNumericIds: true,\n supportsJSON: false,\n supportsArrays: false,\n supportsUUIDs: false,\n transaction,\n };\n}\n\n/**\n * A Better Auth database adapter over a Prisma 8 Postgres or SQLite client.\n *\n * @example\n * ```ts\n * export const auth = betterAuth({ database: prismaAdapter(db) });\n * ```\n */\nexport function prismaAdapter(\n db: PrismaClientLike,\n adapterOptions: PrismaAdapterOptions = {},\n): (betterAuthOptions: BetterAuthOptions) => DBAdapter<BetterAuthOptions> {\n assertClient(db, adapterOptions);\n return (betterAuthOptions) => {\n const context: AdapterContext = {\n orm: db.orm,\n contract: db.contract,\n instance: {\n collections: createModelCollections(db.contract, adapterOptions.namespace),\n defaultSelections: undefined,\n nameCollision: undefined,\n },\n adapterOptions,\n };\n const transaction: AdapterFactoryConfig['transaction'] =\n adapterOptions.transaction === true\n ? (callback) =>\n db.transaction((tx) =>\n callback(\n createAdapterFactory({\n config: factoryConfig(adapterOptions, false),\n adapter: customAdapter({ ...context, orm: tx.orm }),\n })(betterAuthOptions),\n ),\n )\n : false;\n const adapter = createAdapterFactory({\n config: factoryConfig(adapterOptions, transaction),\n adapter: customAdapter(context),\n })(betterAuthOptions);\n registerContractCheck(\n adapter,\n createContractCheck(() => ({\n contract: db.contract,\n tables: getAuthTables(betterAuthOptions),\n betterAuthOptions,\n namespace: adapterOptions.namespace,\n usePlural: adapterOptions.usePlural ?? false,\n })),\n betterAuthOptions,\n );\n return adapter;\n };\n}\n"],"mappings":";;;;;;;;AA+CA,MAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAAgB,gBAAgB,OAAwC;CACtE,OACE,OAAO,UAAU,YACjB,UAAU,QACV,kBAAkB,OAAO,WAAW,OAAO,QAAQ,IAAI,OAAO,MAAM,MAAM,UAAU;AAExF;;AAGA,SAAgB,SAAS,QAAiB,MAAuB;CAC/D,OAAO,OAAO,WAAW,YAAY,WAAW,OAAO,QAAQ,IAAI,QAAQ,IAAI,IAAI,KAAA;AACrF;;AAGA,SAAgB,WAAW,QAAiB,MAAc,GAAG,MAA0B;CACrF,MAAM,SAAS,SAAS,QAAQ,IAAI;CACpC,IAAI,OAAO,WAAW,YAAY,OAAO,KAAA;CACzC,OAAO,QAAQ,MAAM,QAAQ,QAAQ,IAAI;AAC3C;AAEA,SAAgB,UAAU,QAAiB,MAAuB;CAChE,OAAO,OAAO,SAAS,QAAQ,IAAI,MAAM;AAC3C;;AAGA,SAAgB,YAAY,OAA2B;CACrD,OAAO,UAGL,KAAK;AACT;;;;ACzEA,SAAgB,uBACd,UACA,WACkB;CAClB,MAAM,wBAAQ,IAAI,IAAwB;CAC1C,MAAM,eAAe,OAAO,KAAK,SAAS,OAAO,UAAU;CAC3D,MAAM,OAAO,aAAa,WAAW,KAAK,aAAa,OAAO;CAC9D,OAAO;EACL,MAAM,cAAc;GAClB,MAAM,QAAQ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/B,QAAQ,sBAAsB;EAC5B,MAAM,UAA0B;GAC9B,KAAK,GAAG;GACR,UAAU,GAAG;GACb,UAAU;IACR,aAAa,uBAAuB,GAAG,UAAU,eAAe,SAAS;IACzE,mBAAmB,KAAA;IACnB,eAAe,KAAA;GACjB;GACA;EACF;EAaA,MAAM,UAAU,qBAAqB;GACnC,QAAQ,cAAc,gBAZtB,eAAe,gBAAgB,QAC1B,aACC,GAAG,aAAa,OACd,SACE,qBAAqB;IACnB,QAAQ,cAAc,gBAAgB,KAAK;IAC3C,SAAS,cAAc;KAAE,GAAG;KAAS,KAAK,GAAG;IAAI,CAAC;GACpD,CAAC,CAAC,CAAC,iBAAiB,CACtB,CACF,IACF,KAE6C;GACjD,SAAS,cAAc,OAAO;EAChC,CAAC,CAAC,CAAC,iBAAiB;EACpB,sBACE,SACA,2BAA2B;GACzB,UAAU,GAAG;GACb,QAAQ,cAAc,iBAAiB;GACvC;GACA,WAAW,eAAe;GAC1B,WAAW,eAAe,aAAa;EACzC,EAAE,GACF,iBACF;EACA,OAAO;CACT;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prisma/orm-better-auth",
|
|
3
|
-
"version": "8.0.0-rc.25-dev.
|
|
3
|
+
"version": "8.0.0-rc.25-dev.10",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -21,13 +21,15 @@
|
|
|
21
21
|
"@better-auth/scim": "1.7.27",
|
|
22
22
|
"@better-auth/sso": "1.7.27",
|
|
23
23
|
"@better-auth/test-utils": "1.7.27",
|
|
24
|
+
"@prisma/cli-engine": "0.10.4",
|
|
24
25
|
"@prisma/dev": "0.25.2",
|
|
25
|
-
"@prisma/orm-family-sql": "8.0.0-rc.25-dev.
|
|
26
|
-
"@prisma/orm-framework": "8.0.0-rc.25-dev.
|
|
27
|
-
"@prisma/orm-postgres": "8.0.0-rc.25-dev.
|
|
28
|
-
"@prisma/orm-sqlite": "8.0.0-rc.25-dev.
|
|
29
|
-
"@
|
|
30
|
-
"@repo/
|
|
26
|
+
"@prisma/orm-family-sql": "8.0.0-rc.25-dev.10",
|
|
27
|
+
"@prisma/orm-framework": "8.0.0-rc.25-dev.10",
|
|
28
|
+
"@prisma/orm-postgres": "8.0.0-rc.25-dev.10",
|
|
29
|
+
"@prisma/orm-sqlite": "8.0.0-rc.25-dev.10",
|
|
30
|
+
"@prisma/orm-toolchain": "8.0.0-rc.25-dev.10",
|
|
31
|
+
"@repo/tsconfig": "8.0.0-rc.25-dev.10",
|
|
32
|
+
"@repo/tsdown": "8.0.0-rc.25-dev.10",
|
|
31
33
|
"@types/node": "26.1.2",
|
|
32
34
|
"@types/pg": "8.20.4",
|
|
33
35
|
"better-auth": "1.7.27",
|
|
@@ -39,9 +41,10 @@
|
|
|
39
41
|
"vitest": "5.0.0-rc.2"
|
|
40
42
|
},
|
|
41
43
|
"peerDependencies": {
|
|
42
|
-
"@better-auth/core": ">=1.7.
|
|
43
|
-
"@prisma/orm-family-sql": "8.0.0-rc.25-dev.
|
|
44
|
-
"@prisma/orm-framework": "8.0.0-rc.25-dev.
|
|
44
|
+
"@better-auth/core": ">=1.7.22 <1.8.0",
|
|
45
|
+
"@prisma/orm-family-sql": "8.0.0-rc.25-dev.10",
|
|
46
|
+
"@prisma/orm-framework": "8.0.0-rc.25-dev.10",
|
|
47
|
+
"@prisma/orm-toolchain": "8.0.0-rc.25-dev.10",
|
|
45
48
|
"typescript": ">=5.9"
|
|
46
49
|
},
|
|
47
50
|
"peerDependenciesMeta": {
|