@prisma/orm-better-auth 8.0.1-dev.7 → 8.0.1-dev.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,4 @@
1
1
  import { DBAdapter, DBAdapterDebugLogOption } from "@better-auth/core/db/adapter";
2
- import { SqlRuntimeTargetDescriptor } from "@prisma/orm-family-sql/runtime";
3
2
  import { BetterAuthOptions } from "@better-auth/core";
4
3
  import { SqlStorage } from "@prisma/orm-family-sql/contract/types";
5
4
  import { Contract } from "@prisma/orm-framework/contract/types";
@@ -21,10 +20,6 @@ interface PrismaAdapterOptions {
21
20
  interface PrismaClientLike {
22
21
  readonly contract: SqlContract;
23
22
  readonly orm: object;
24
- /** The client's stack, whose target names the capabilities it retired. Prisma 8.0 removes this field. */
25
- readonly stack?: {
26
- readonly target: Pick<SqlRuntimeTargetDescriptor, 'retiredCapabilities'>;
27
- };
28
23
  }
29
24
  /** A client that runs interactive transactions, which the `transaction` option needs. */
30
25
  interface TransactionalPrismaClientLike extends PrismaClientLike {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/models/model-lookup.ts","../src/options.ts","../src/adapter.ts"],"mappings":";;;;;;KAIY,cAAc,SAAS;;;UCFlB;WACN;WACA;WACA;WACA,YAAY;;;;;;;UC+BN;WACN,UAAU;WACV;;WAEA;aACE,QAAQ,KAAK;;;;UAKT,sCAAsC;EACrD,YAAY,GAAG,KAAK;aAAe;QAAkB,YAAY,KAAK,QAAQ;;;KAIpE,oBAAoB,gBAAgB,oDAClB,uBACX,8BAA8B,WACzC,gCACA,mBACF;;;;;;;;;iBAsSU,oBAAoB,gBAAgB,uBAAuB,sBACzE,IAAI,oBAAoB,UACxB,iBAAiB,WACf,mBAAmB,sBAAsB,UAAU"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/models/model-lookup.ts","../src/options.ts","../src/adapter.ts"],"mappings":";;;;;KAIY,cAAc,SAAS;;;UCFlB;WACN;WACA;WACA;WACA,YAAY;;;;;;;UC4BN;WACN,UAAU;WACV;;;UAIM,sCAAsC;EACrD,YAAY,GAAG,KAAK;aAAe;QAAkB,YAAY,KAAK,QAAQ;;;KAIpE,oBAAoB,gBAAgB,oDAClB,uBACX,8BAA8B,WACzC,gCACA,mBACF;;;;;;;;;iBAsSU,oBAAoB,gBAAgB,uBAAuB,sBACzE,IAAI,oBAAoB,UACxB,iBAAiB,WACf,mBAAmB,sBAAsB,UAAU"}
package/dist/index.mjs CHANGED
@@ -227,7 +227,7 @@ function assertClient(db, adapterOptions) {
227
227
  if (namespace !== void 0 && !Object.hasOwn(contract.domain.namespaces, namespace)) throw new BetterAuthError(`Namespace "${namespace}" is not in your Prisma contract.`);
228
228
  if (adapterOptions.transaction !== true) return;
229
229
  if (!hasTransaction(db)) throw new BetterAuthError("The transaction option runs Better Auth transactions through the client's transaction(), which this object does not have. Pass the Prisma client, or turn the option off.");
230
- if (!interactiveTransactionsAvailable(contract, db.stack?.target.retiredCapabilities)) throw new BetterAuthError(capabilityUnavailableMessage("The transaction option", ["sql.interactiveTransactions"], "The option runs Better Auth transactions through the client's `transaction()`, which needs it."));
230
+ if (!interactiveTransactionsAvailable(contract)) throw new BetterAuthError(capabilityUnavailableMessage("The transaction option", ["conn.interactiveTransactions"], "The option runs Better Auth transactions through the client's `transaction()`, which needs it."));
231
231
  }
232
232
  /** For each physical model name, the fields a read without `select` returns: `id` and every field of Better Auth's table description. */
233
233
  function defaultSelections(schema, betterAuthOptions, usePlural) {
@@ -1 +1 @@
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 { capabilityUnavailableMessage } from '@prisma/orm-family-sql/contract/capability-messages';\nimport {\n interactiveTransactionsAvailable,\n type SqlRuntimeTargetDescriptor,\n} from '@prisma/orm-family-sql/runtime';\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 /** The client's stack, whose target names the capabilities it retired. Prisma 8.0 removes this field. */\n readonly stack?: {\n readonly target: Pick<SqlRuntimeTargetDescriptor, 'retiredCapabilities'>;\n };\n}\n\n/** A client that runs interactive transactions, which the `transaction` option needs. */\nexport interface TransactionalPrismaClientLike extends PrismaClientLike {\n transaction<R>(fn: (tx: { readonly orm: object }) => PromiseLike<R>): Promise<R>;\n}\n\n/** The client `prismaAdapter` takes: one with `transaction()` when `transaction` may be on. */\nexport type PrismaClientLikeFor<Options extends PrismaAdapterOptions> =\n 'transaction' extends keyof Options\n ? true extends Options['transaction' & keyof Options]\n ? TransactionalPrismaClientLike\n : PrismaClientLike\n : PrismaClientLike;\n\nfunction hasTransaction(db: PrismaClientLike): db is TransactionalPrismaClientLike {\n return 'transaction' in db && typeof db.transaction === 'function';\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 if (adapterOptions.transaction !== true) return;\n if (!hasTransaction(db)) {\n throw new BetterAuthError(\n \"The transaction option runs Better Auth transactions through the client's transaction(), which this object does not have. Pass the Prisma client, or turn the option off.\",\n );\n }\n if (!interactiveTransactionsAvailable(contract, db.stack?.target.retiredCapabilities)) {\n throw new BetterAuthError(\n capabilityUnavailableMessage(\n 'The transaction option',\n ['sql.interactiveTransactions'],\n \"The option runs Better Auth transactions through the client's `transaction()`, which needs it.\",\n ),\n );\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<const Options extends PrismaAdapterOptions = Record<never, never>>(\n db: PrismaClientLikeFor<Options>,\n adapterOptions?: Options,\n): (betterAuthOptions: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;\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 && hasTransaction(db)\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;CAC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,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,QAAQ,eAAe,EAAE,KACnD,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 { capabilityUnavailableMessage } from '@prisma/orm-family-sql/contract/capability-messages';\nimport { interactiveTransactionsAvailable } from '@prisma/orm-family-sql/runtime';\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}\n\n/** A client that runs interactive transactions, which the `transaction` option needs. */\nexport interface TransactionalPrismaClientLike extends PrismaClientLike {\n transaction<R>(fn: (tx: { readonly orm: object }) => PromiseLike<R>): Promise<R>;\n}\n\n/** The client `prismaAdapter` takes: one with `transaction()` when `transaction` may be on. */\nexport type PrismaClientLikeFor<Options extends PrismaAdapterOptions> =\n 'transaction' extends keyof Options\n ? true extends Options['transaction' & keyof Options]\n ? TransactionalPrismaClientLike\n : PrismaClientLike\n : PrismaClientLike;\n\nfunction hasTransaction(db: PrismaClientLike): db is TransactionalPrismaClientLike {\n return 'transaction' in db && typeof db.transaction === 'function';\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 if (adapterOptions.transaction !== true) return;\n if (!hasTransaction(db)) {\n throw new BetterAuthError(\n \"The transaction option runs Better Auth transactions through the client's transaction(), which this object does not have. Pass the Prisma client, or turn the option off.\",\n );\n }\n if (!interactiveTransactionsAvailable(contract)) {\n throw new BetterAuthError(\n capabilityUnavailableMessage(\n 'The transaction option',\n ['conn.interactiveTransactions'],\n \"The option runs Better Auth transactions through the client's `transaction()`, which needs it.\",\n ),\n );\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<const Options extends PrismaAdapterOptions = Record<never, never>>(\n db: PrismaClientLikeFor<Options>,\n adapterOptions?: Options,\n): (betterAuthOptions: BetterAuthOptions) => DBAdapter<BetterAuthOptions>;\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 && hasTransaction(db)\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,QAA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;CACT;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/orm-better-auth",
3
- "version": "8.0.1-dev.7",
3
+ "version": "8.0.1-dev.8",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -23,13 +23,13 @@
23
23
  "@better-auth/test-utils": "1.7.27",
24
24
  "@prisma/cli-engine": "0.10.4",
25
25
  "@prisma/dev": "0.25.2",
26
- "@prisma/orm-family-sql": "8.0.1-dev.7",
27
- "@prisma/orm-framework": "8.0.1-dev.7",
28
- "@prisma/orm-postgres": "8.0.1-dev.7",
29
- "@prisma/orm-sqlite": "8.0.1-dev.7",
30
- "@prisma/orm-toolchain": "8.0.1-dev.7",
31
- "@repo/tsconfig": "8.0.1-dev.7",
32
- "@repo/tsdown": "8.0.1-dev.7",
26
+ "@prisma/orm-family-sql": "8.0.1-dev.8",
27
+ "@prisma/orm-framework": "8.0.1-dev.8",
28
+ "@prisma/orm-postgres": "8.0.1-dev.8",
29
+ "@prisma/orm-sqlite": "8.0.1-dev.8",
30
+ "@prisma/orm-toolchain": "8.0.1-dev.8",
31
+ "@repo/tsconfig": "8.0.1-dev.8",
32
+ "@repo/tsdown": "8.0.1-dev.8",
33
33
  "@types/node": "26.1.2",
34
34
  "@types/pg": "8.20.4",
35
35
  "better-auth": "1.7.27",
@@ -42,9 +42,9 @@
42
42
  },
43
43
  "peerDependencies": {
44
44
  "@better-auth/core": ">=1.7.22 <1.8.0",
45
- "@prisma/orm-family-sql": "8.0.1-dev.7",
46
- "@prisma/orm-framework": "8.0.1-dev.7",
47
- "@prisma/orm-toolchain": "8.0.1-dev.7",
45
+ "@prisma/orm-family-sql": "8.0.1-dev.8",
46
+ "@prisma/orm-framework": "8.0.1-dev.8",
47
+ "@prisma/orm-toolchain": "8.0.1-dev.8",
48
48
  "typescript": ">=5.9"
49
49
  },
50
50
  "peerDependenciesMeta": {