@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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract-check-Cw4rCQvX.mjs","names":[],"sources":["../src/models/identifiers.ts","../src/models/model-lookup.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"],"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/** The contract model names a Better Auth physical model name is looked up by, in order: the exact name, then the name with its first letter upper-cased. */\nexport function modelNameCandidates(physicalName: string): readonly string[] {\n return [...new Set([physicalName, upperFirst(physicalName)])];\n}\n\n/** Whether the adapter looks for Better Auth's models in a namespace: every namespace without the adapter's `namespace` option, else only the one it names. */\nexport function isSearchedNamespace(namespaceId: string, namespace: string | undefined): boolean {\n return namespace === undefined || namespaceId === namespace;\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 = Object.keys(namespaces).filter((id) => isSearchedNamespace(id, namespace));\n for (const name of modelNameCandidates(physicalName)) {\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 { 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 /** Whether the database treats table and column names that differ only in the case of the letters A to Z as the same name. */\n readonly storageNamesIgnoreCase: boolean;\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 storageNamesIgnoreCaseByTarget: Readonly<Record<string, boolean>> = {\n sqlite: true,\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 storageNamesIgnoreCase = storageNamesIgnoreCaseByTarget[contract.target] ?? false;\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 storageNamesIgnoreCase,\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 storageNamesIgnoreCase,\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 namespaceId: string;\n readonly existing: boolean;\n /** Better Auth's physical name of a missing model, which the adapter looks the model up by; `undefined` for an existing model. */\n readonly physicalName: string | undefined;\n /** The table a missing model is stored in; `undefined` for an existing model. */\n readonly table: string | undefined;\n /** The columns of the scalar fields the block adds to an existing model. */\n readonly columns: readonly string[];\n readonly fieldNames: readonly string[];\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 physicalName: string | undefined;\n readonly table: string | undefined;\n readonly columns: string[];\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 physicalName: undefined,\n table: undefined,\n columns: [],\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 physicalName: model.expected.physicalName,\n table: model.expected.physicalName,\n columns: [],\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. */\nexport function renderBlocks(\n blocks: readonly PrintedBlock[],\n namespace: string | undefined,\n): 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 holder.columns.push(name);\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 used 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 namespaceId: printed.namespaceId,\n existing: printed.existing,\n physicalName: printed.physicalName,\n table: printed.table,\n columns: printed.columns,\n fieldNames: lines.map(([name]) => name),\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.registerSchemaC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A,GACd,IAAI;GACF,MAAM,QAAQ,iBAAiB,MAAM,CAAC;GACtC,UAAU,UAAU,KAAA,IAAY,EAAE,OAAO,KAAK,IAAI;IAAE,OAAO;IAAO;GAAM;EAC1E,SAAS,OAAO;GACd,UAAU;IAAE,OAAO;IAAO;GAAM;EAClC;EAEF,OAAO,QAAQ,QAAQ,KAAA,IAAY,QAAQ,OAAO,QAAQ,KAAK;CACjE;AACF;;;;AAKA,SAAgB,sBACd,SACA,OACA,mBACM;CACN,IAAI,OAAO,SAAS,wBAAwB,YAAY;CACxD,SAAS,oBAAoB,SAAS,OAAO,EAC3C,gBAAgB,kBAAkB,UAAU,UAAU,mBAAmB,MAC3E,CAAC;AACH"}
@@ -0,0 +1,487 @@
1
+ import { a as printPsl, g as modelNameCandidates, i as contractMessage, m as isSearchedNamespace, o as renderBlocks, t as contractMismatchError } from "./contract-check-Cw4rCQvX.mjs";
2
+ import { buildSymbolTable, isPrisma8Schema } from "@prisma/orm-framework/psl-parser";
3
+ import { CompositeTypeDeclarationAst, GenericBlockDeclarationAst, MixinDeclarationAst, ModelDeclarationAst, NamespaceDeclarationAst, StringLiteralExprAst, TypesBlockAst, parse } from "@prisma/orm-framework/psl-parser/syntax";
4
+ //#region src/generate/refusal.ts
5
+ const additionKinds = /* @__PURE__ */ new Set(["missing-model", "missing-field"]);
6
+ /** The error `auth generate` throws when it writes nothing: the contract message, then why the contract was not changed. */
7
+ function notChanged(comparison, reason) {
8
+ const message = contractMessage(comparison) ?? "";
9
+ return contractMismatchError(reason === void 0 ? message : `${message}\n\n\`auth generate\` did not change your contract, because ${reason}`);
10
+ }
11
+ /** Throws the contract message when the comparison found something other than a missing model or field, which `auth generate` does not fix. */
12
+ function assertOnlyAdditions(comparison) {
13
+ if (comparison.problems.some((problem) => !additionKinds.has(problem.kind))) throw notChanged(comparison);
14
+ }
15
+ function listOf(items) {
16
+ const last = items.at(-1);
17
+ return items.length < 2 || last === void 0 ? items.join("") : `${items.slice(0, -1).join(", ")} and ${last}`;
18
+ }
19
+ //#endregion
20
+ //#region src/generate/contract-source-files.ts
21
+ const passOutput = "Pass your contract file with `--output`.";
22
+ const typeScriptContract = "it is written in TypeScript. Add the equivalent models and fields in TypeScript.";
23
+ const typeScriptFile = /\.[cm]?tsx?$/;
24
+ const betterAuthDirectoryFile = "auth-schema.ts";
25
+ /** A caught error's code, as the operating system and the module loader give one, in parentheses; nothing when it has none. Their messages are left out: they differ between systems and hold absolute paths. */
26
+ function errorCode(error) {
27
+ const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
28
+ return typeof code === "string" ? ` (${code})` : "";
29
+ }
30
+ /** A caught error's code, or else the first line of its message. Used where an error without a code comes from the developer's own `prisma.config.ts` or file, whose text is what they need. */
31
+ function errorDetail(error) {
32
+ const code = errorCode(error);
33
+ if (code !== "") return code;
34
+ return `: ${(error instanceof Error ? error.message : String(error)).split("\n")[0]}`;
35
+ }
36
+ function isMissingFile(error) {
37
+ return error instanceof Error && Reflect.get(error, "code") === "ENOENT";
38
+ }
39
+ async function configLoader(comparison) {
40
+ try {
41
+ return await import("@prisma/orm-toolchain/config-loader");
42
+ } catch (error) {
43
+ throw notChanged(comparison, `Prisma's config loader could not be loaded${errorCode(error)}. ${passOutput}`);
44
+ }
45
+ }
46
+ /** The absolute paths of the contract's inputs in `prisma.config.ts` in the working directory. Better Auth does not tell the adapter its `--cwd`. */
47
+ async function contractInputs(comparison, shown) {
48
+ const loader = await configLoader(comparison);
49
+ const didNotLoad = (reason) => notChanged(comparison, `prisma.config.ts did not load${reason}. ${passOutput}`);
50
+ let loaded;
51
+ try {
52
+ loaded = await loader.loadConfigForSections(void 0, ["contract"]);
53
+ } catch (error) {
54
+ throw didNotLoad(errorDetail(error));
55
+ }
56
+ if (!loaded.ok) {
57
+ if (loaded.failure.code === "CONFIG.FILE_NOT_FOUND") throw notChanged(comparison, `it found no prisma.config.ts in the working directory. ${passOutput}`);
58
+ throw didNotLoad(`: ${loaded.failure.message}`);
59
+ }
60
+ const source = loaded.value.contract?.source;
61
+ if (source === void 0) throw notChanged(comparison, `prisma.config.ts names no contract. ${passOutput}`);
62
+ if (source.format !== "psl") throw notChanged(comparison, typeScriptContract);
63
+ if (source.parserOptions?.grammar === "prisma-7") throw notChanged(comparison, "it is a Prisma 7 schema, and the lines above are Prisma 8 syntax. Add the equivalent lines by hand.");
64
+ const inputs = await loader.expandContractInputs(source.inputs);
65
+ if (inputs.length === 0) throw notChanged(comparison, `the contract inputs prisma.config.ts names match no file: ${(source.inputs ?? []).map(shown).join(", ")}. ${passOutput}`);
66
+ return inputs;
67
+ }
68
+ /**
69
+ * The contract's source files: the file `--output` names when Better Auth passes one, otherwise the files of the contract in `prisma.config.ts` in the working directory that start with `// use prisma-8`, as emitting reads them. Each file's `path` is relative to the working directory when the file is inside it. Throws the contract message, with the reason, when no PSL source can be read.
70
+ */
71
+ async function contractSourceFiles(file, comparison) {
72
+ const { readFile } = await import("node:fs/promises");
73
+ const { basename, isAbsolute, relative, resolve } = await import("node:path");
74
+ const shown = (path) => {
75
+ const fromCwd = relative(process.cwd(), path);
76
+ return fromCwd.startsWith("..") || isAbsolute(fromCwd) ? path : fromCwd;
77
+ };
78
+ if (file !== void 0 && typeScriptFile.test(file)) throw notChanged(comparison, basename(file) === betterAuthDirectoryFile ? `\`--output\` names a directory, so Better Auth passed ${shown(resolve(file))}. Pass your contract's PSL file itself with \`--output\`.` : typeScriptContract);
79
+ const paths = file === void 0 ? await contractInputs(comparison, shown) : [resolve(file)];
80
+ const files = [];
81
+ for (const absolutePath of paths) {
82
+ const path = shown(absolutePath);
83
+ let text;
84
+ try {
85
+ text = await readFile(absolutePath, "utf8");
86
+ } catch (error) {
87
+ throw notChanged(comparison, isMissingFile(error) ? `${path} was not found. ${passOutput}` : `${path} could not be read${errorDetail(error)}. ${passOutput}`);
88
+ }
89
+ if (file === void 0 && !isPrisma8Schema(text)) continue;
90
+ files.push({
91
+ path,
92
+ text,
93
+ absolutePath
94
+ });
95
+ }
96
+ if (files.length === 0) throw notChanged(comparison, `none of the files prisma.config.ts names starts with \`// use prisma-8\`. ${passOutput}`);
97
+ return files;
98
+ }
99
+ //#endregion
100
+ //#region src/generate/check-edited-source.ts
101
+ function offsetOf(text, line, character) {
102
+ let offset = 0;
103
+ for (let current = 0; current < line; current += 1) {
104
+ const newline = text.indexOf("\n", offset);
105
+ if (newline === -1) return text.length;
106
+ offset = newline + 1;
107
+ }
108
+ return offset + character;
109
+ }
110
+ /** What Prisma's published parser and symbol table report for a contract's source files: parse errors and duplicate declarations. */
111
+ function diagnosticsOf(files, defaultNamespaceId) {
112
+ const parsed = files.map((file) => parse(file.text, file.path));
113
+ const [first, ...rest] = parsed.map(({ sources }) => sources);
114
+ if (first === void 0) return [];
115
+ const { diagnostics } = buildSymbolTable({
116
+ documents: parsed.map(({ document }) => document),
117
+ sources: first.merge(...rest),
118
+ defaultNamespaceId
119
+ });
120
+ const textOf = new Map(files.map((file) => [file.path, file.text]));
121
+ return [...parsed.flatMap((result) => result.diagnostics), ...diagnostics].map(({ filename, message, range }) => ({
122
+ path: filename,
123
+ message,
124
+ line: range.start.line + 1,
125
+ offset: offsetOf(textOf.get(filename) ?? "", range.start.line, range.start.character)
126
+ }));
127
+ }
128
+ function keyOf({ path, message, offset }) {
129
+ return `${path}\u0000${message}\u0000${offset}`;
130
+ }
131
+ /**
132
+ * The first diagnostic the edited files have and the original files do not. Each original diagnostic is moved by the text the edit inserted before it, so a diagnostic the original already had is matched where it now is, and the one returned is where the edit put it. The check is what a published entrypoint offers without the target's descriptors: parsing and the symbol table, not the binder or interpreter.
133
+ */
134
+ function firstNewDiagnostic(original, edited, defaultNamespaceId, inserted) {
135
+ const remaining = /* @__PURE__ */ new Map();
136
+ for (const diagnostic of diagnosticsOf(original, defaultNamespaceId)) {
137
+ const shift = inserted.filter(({ path, offset }) => path === diagnostic.path && offset <= diagnostic.offset).reduce((total, { length }) => total + length, 0);
138
+ const key = keyOf({
139
+ ...diagnostic,
140
+ offset: diagnostic.offset + shift
141
+ });
142
+ remaining.set(key, (remaining.get(key) ?? 0) + 1);
143
+ }
144
+ for (const diagnostic of diagnosticsOf(edited, defaultNamespaceId)) {
145
+ const key = keyOf(diagnostic);
146
+ const left = remaining.get(key) ?? 0;
147
+ if (left === 0) return {
148
+ path: diagnostic.path,
149
+ message: diagnostic.message,
150
+ line: diagnostic.line
151
+ };
152
+ remaining.set(key, left - 1);
153
+ }
154
+ }
155
+ //#endregion
156
+ //#region src/generate/edit-contract-source.ts
157
+ function modelKey(namespaceId, name) {
158
+ return `${namespaceId}.${name}`;
159
+ }
160
+ /** The kind of a declaration that shares the name slot of models, or `undefined` for a model or a declaration that does not. Read from `buildSymbolTable` in `psl-parser/src/symbol-table.ts`. */
161
+ function otherKind(declaration) {
162
+ if (declaration instanceof CompositeTypeDeclarationAst) return "composite type";
163
+ if (declaration instanceof MixinDeclarationAst) return "mixin";
164
+ if (declaration instanceof GenericBlockDeclarationAst) return declaration.keyword()?.text ?? "block";
165
+ }
166
+ function declaredFields(fields) {
167
+ return [...fields].flatMap((field) => {
168
+ const name = field.name()?.name();
169
+ return name === void 0 ? [] : [{
170
+ name,
171
+ column: mappedName(field.attributes()) ?? name
172
+ }];
173
+ });
174
+ }
175
+ /** The model's fields as the contract will have them: its own, then those of every mixin it includes. */
176
+ function modelFields({ file, declaration }, mixins) {
177
+ const own = declaredFields(declaration.fields()).map((field) => ({
178
+ ...field,
179
+ mixin: void 0,
180
+ path: file.path
181
+ }));
182
+ const included = [...declaration.inclusions()].flatMap((inclusion) => {
183
+ const mixinName = inclusion.name()?.path().at(-1);
184
+ return mixins.filter(({ name }) => name === mixinName).flatMap((mixin) => mixin.fields.map((field) => ({
185
+ ...field,
186
+ mixin: mixin.name,
187
+ path: mixin.path
188
+ })));
189
+ });
190
+ return [...own, ...included];
191
+ }
192
+ function collectDeclarations(file, document, defaultNamespace, into) {
193
+ const add = (namespaceId, declaration) => {
194
+ const name = declaration.name()?.name();
195
+ if (name === void 0) return;
196
+ if (declaration instanceof ModelDeclarationAst) {
197
+ const key = modelKey(namespaceId, name);
198
+ into.models.set(key, [...into.models.get(key) ?? [], {
199
+ file,
200
+ namespaceId,
201
+ declaration
202
+ }]);
203
+ return;
204
+ }
205
+ if (declaration instanceof MixinDeclarationAst) into.mixins.push({
206
+ name,
207
+ path: file.path,
208
+ fields: declaredFields(declaration.fields())
209
+ });
210
+ const kind = otherKind(declaration);
211
+ if (kind !== void 0) into.others.push({
212
+ path: file.path,
213
+ namespaceId,
214
+ name,
215
+ kind
216
+ });
217
+ };
218
+ for (const declaration of document.declarations()) {
219
+ if (declaration instanceof ModelDeclarationAst || declaration instanceof CompositeTypeDeclarationAst || declaration instanceof GenericBlockDeclarationAst || declaration instanceof MixinDeclarationAst) {
220
+ add(defaultNamespace, declaration);
221
+ continue;
222
+ }
223
+ if (declaration instanceof TypesBlockAst) {
224
+ for (const binding of declaration.declarations()) {
225
+ const name = binding.name()?.name();
226
+ if (name !== void 0) into.others.push({
227
+ path: file.path,
228
+ namespaceId: defaultNamespace,
229
+ name,
230
+ kind: "named type"
231
+ });
232
+ }
233
+ continue;
234
+ }
235
+ if (!(declaration instanceof NamespaceDeclarationAst)) continue;
236
+ const namespaceName = declaration.name()?.name();
237
+ if (namespaceName !== void 0) into.others.push({
238
+ path: file.path,
239
+ namespaceId: defaultNamespace,
240
+ name: namespaceName,
241
+ kind: "namespace"
242
+ });
243
+ const namespaceId = namespaceName ?? defaultNamespace;
244
+ for (const member of declaration.declarations()) if (member instanceof ModelDeclarationAst || member instanceof CompositeTypeDeclarationAst || member instanceof GenericBlockDeclarationAst || member instanceof MixinDeclarationAst) add(namespaceId, member);
245
+ }
246
+ }
247
+ function parsedDeclarations(files, comparison) {
248
+ const declarations = {
249
+ models: /* @__PURE__ */ new Map(),
250
+ others: [],
251
+ mixins: []
252
+ };
253
+ for (const file of files) {
254
+ if (!isPrisma8Schema(file.text)) throw notChanged(comparison, `${file.path} does not start with \`// use prisma-8\`.`);
255
+ const { document, diagnostics } = parse(file.text, file.path);
256
+ const [first] = diagnostics;
257
+ if (first !== void 0) throw notChanged(comparison, `${file.path} does not parse: ${first.message} (line ${first.range.start.line + 1}).`);
258
+ collectDeclarations(file, document, comparison.defaultNamespace, declarations);
259
+ }
260
+ return declarations;
261
+ }
262
+ /** The name `@map("x")` or `@@map("x")` gives, read as the contract emitter reads it: the first `map` attribute, and its first positional argument when that is a string. */
263
+ function mappedName(attributes) {
264
+ for (const attribute of attributes) {
265
+ const path = attribute.name()?.path() ?? [];
266
+ if (path.length !== 1 || path[0] !== "map") continue;
267
+ const [first] = [...attribute.argList()?.args() ?? []].filter((argument) => argument.name() === void 0);
268
+ const value = first?.value();
269
+ return value instanceof StringLiteralExprAst ? value.value() : void 0;
270
+ }
271
+ }
272
+ /** The name with only the ASCII letters A to Z lower-cased, the case SQLite ignores in table and column names. */
273
+ function foldAsciiCase(name) {
274
+ return name.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
275
+ }
276
+ function sameStorageName(a, b, comparison) {
277
+ return comparison.storageNamesIgnoreCase ? foldAsciiCase(a) === foldAsciiCase(b) : a === b;
278
+ }
279
+ /** What the model already declares that conflicts with the fields the block would add. A Better Auth field is found by its exact name. */
280
+ function fieldConflicts(block, model, mixins, comparison, into) {
281
+ const additions = new Set(block.fieldNames);
282
+ for (const { name, column, mixin, path } of modelFields(model, mixins)) {
283
+ const declared = `${block.modelName}.${name}${mixin === void 0 ? "" : ` (from the mixin ${mixin})`}`;
284
+ if (additions.has(name)) {
285
+ into.aheadOfEmit.push({
286
+ name: declared,
287
+ namespaceId: void 0,
288
+ path
289
+ });
290
+ continue;
291
+ }
292
+ const needed = block.columns.find((candidate) => sameStorageName(candidate, column, comparison));
293
+ if (needed === void 0) continue;
294
+ into.storedUnderAnotherName.push({
295
+ path,
296
+ declared,
297
+ storage: `the column "${column}"`,
298
+ lookedFor: `a field named ${needed} in ${block.modelName}`,
299
+ renameTo: needed
300
+ });
301
+ }
302
+ }
303
+ /**
304
+ * The declared models that conflict with a model the block would add: one with a name the adapter looks the model up by, in a namespace the adapter searches; or one stored in its table, in the namespace the model goes into.
305
+ */
306
+ function modelConflicts(block, models, comparison, into) {
307
+ const { physicalName, table } = block;
308
+ if (physicalName === void 0 || table === void 0) return;
309
+ const lookedUp = new Set(modelNameCandidates(physicalName));
310
+ const newNamespace = comparison.namespace ?? comparison.defaultNamespace;
311
+ for (const { file, namespaceId, declaration } of models) {
312
+ const name = declaration.name()?.name();
313
+ if (name === void 0) continue;
314
+ if (lookedUp.has(name) && isSearchedNamespace(namespaceId, comparison.namespace)) {
315
+ into.aheadOfEmit.push({
316
+ name,
317
+ namespaceId,
318
+ path: file.path
319
+ });
320
+ continue;
321
+ }
322
+ if (namespaceId !== newNamespace) continue;
323
+ const stored = mappedName(declaration.attributes()) ?? name;
324
+ if (!sameStorageName(stored, table, comparison)) continue;
325
+ into.storedUnderAnotherName.push({
326
+ path: file.path,
327
+ declared: name,
328
+ storage: `the table "${stored}"`,
329
+ lookedFor: `a model named ${block.modelName}`,
330
+ renameTo: block.modelName
331
+ });
332
+ }
333
+ }
334
+ /** The listed names, each prefixed with its namespace when another listed name is the same. */
335
+ function aheadOfEmitNames(declarations) {
336
+ return declarations.map(({ name, namespaceId }) => namespaceId !== void 0 && declarations.filter((other) => other.name === name).length > 1 ? `${namespaceId}.${name}` : name);
337
+ }
338
+ function storedUnderAnotherNameReason({ path, declared, storage, lookedFor, renameTo }) {
339
+ return `${path} stores ${declared} in ${storage}, but Better Auth looks for ${lookedFor}. Rename ${declared} to ${renameTo}, then run \`prisma contract emit\`, and \`auth generate\` again.`;
340
+ }
341
+ function uniquePaths(models) {
342
+ return [...new Set(models.map(({ file }) => file.path))];
343
+ }
344
+ function lineStart(text, offset) {
345
+ return text.lastIndexOf("\n", offset - 1) + 1;
346
+ }
347
+ /** The offset of the line break that ends the line holding `offset`, before `\r\n` or `\n`, or the end of the text. */
348
+ function lineEnd(text, offset) {
349
+ const newline = text.indexOf("\n", offset);
350
+ if (newline === -1) return text.length;
351
+ return text[newline - 1] === "\r" ? newline - 1 : newline;
352
+ }
353
+ function indentationAt(text, offset) {
354
+ return /^[ \t]*/.exec(text.slice(lineStart(text, offset)))?.[0] ?? "";
355
+ }
356
+ /** The indentation of a field relative to its model, from the first model of the file that has a field; two spaces when none has. */
357
+ function indentUnit(text, models) {
358
+ for (const { declaration } of [...models].sort((a, b) => a.declaration.syntax.offset - b.declaration.syntax.offset)) {
359
+ const [field] = declaration.fields();
360
+ if (field === void 0) continue;
361
+ const modelIndent = indentationAt(text, declaration.syntax.offset);
362
+ const fieldIndent = indentationAt(text, field.syntax.offset);
363
+ if (fieldIndent.length > modelIndent.length && fieldIndent.startsWith(modelIndent)) return fieldIndent.slice(modelIndent.length);
364
+ }
365
+ return " ";
366
+ }
367
+ /** Printed PSL, indented two spaces a level, with each level indented by `unit` instead. */
368
+ function reindented(printed, unit) {
369
+ return printed.replace(/^(?: {2})+/gm, (spaces) => unit.repeat(spaces.length / 2));
370
+ }
371
+ /** Where the block's fields go: after the line of the model's last field, or after the `{` line of a model without fields. `undefined` when the model's `}` is on that line. */
372
+ function fieldInsertion(text, declaration, block, eol, unit) {
373
+ const last = [...declaration.fields()].at(-1);
374
+ const anchorEnd = last?.syntax.endOffset ?? declaration.lbrace()?.endOffset;
375
+ const rbrace = declaration.rbrace();
376
+ if (anchorEnd === void 0 || rbrace === void 0) return void 0;
377
+ const offset = lineEnd(text, anchorEnd);
378
+ if (rbrace.offset < offset) return void 0;
379
+ const indent = last === void 0 ? `${indentationAt(text, declaration.syntax.offset)}${unit}` : indentationAt(text, last.syntax.offset);
380
+ return {
381
+ offset,
382
+ text: block.fieldLines.map((line) => `${eol}${indent}${line}`).join("")
383
+ };
384
+ }
385
+ function separatorBefore(text, eol) {
386
+ if (text.endsWith(`${eol}${eol}`)) return "";
387
+ return text.endsWith(eol) ? eol : `${eol}${eol}`;
388
+ }
389
+ function countOf(count, noun) {
390
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
391
+ }
392
+ function summaryOf(path, extended, added, notes) {
393
+ const parts = extended.map((block) => `${countOf(block.fieldNames.length, "field")} added to ${block.modelName}`);
394
+ if (added.length > 0) parts.push(`model${added.length === 1 ? "" : "s"} ${listOf(added.map((block) => block.modelName))} added`);
395
+ return [`Changes to ${path}: ${parts.join(", ")}. After the file is written, run \`prisma contract emit\` and update your database.`, ...notes.map((note) => `Note: ${note}`)].join("\n");
396
+ }
397
+ /**
398
+ * Adds what the comparison found missing to the PSL source files, as text inserted at positions from the syntax tree: missing fields after the last field of their model, missing models at the end of the file that holds the first model the edit extends. Every original line is kept as written. Throws the contract message, with the reason, when the edit cannot be made.
399
+ */
400
+ function editContractSource(files, comparison) {
401
+ assertOnlyAdditions(comparison);
402
+ const withoutId = comparison.models.find((model) => model.status === "found" && model.missingFields.includes("id"));
403
+ if (withoutId?.status === "found") throw notChanged(comparison, `model ${withoutId.found.name} has no field named \`id\`. Add the \`id\` field above by hand, with \`@unique\` in place of \`@id\`.`);
404
+ const { models: declared, others, mixins } = parsedDeclarations(files, comparison);
405
+ const printed = printPsl(comparison);
406
+ const extended = printed.blocks.filter((block) => block.existing);
407
+ const added = printed.blocks.filter((block) => !block.existing);
408
+ const targets = extended.map((block) => {
409
+ const matches = declared.get(modelKey(block.namespaceId, block.modelName)) ?? [];
410
+ const [match] = matches;
411
+ if (match === void 0) throw notChanged(comparison, `no model ${block.modelName} is declared in ${listOf(files.map((file) => file.path))}.`);
412
+ if (matches.length > 1) throw notChanged(comparison, `model ${block.modelName} is declared more than once in ${listOf(uniquePaths(matches))}.`);
413
+ return {
414
+ block,
415
+ ...match
416
+ };
417
+ });
418
+ const allDeclared = [...declared.values()].flat();
419
+ const conflicts = {
420
+ aheadOfEmit: [],
421
+ storedUnderAnotherName: []
422
+ };
423
+ for (const { block, ...model } of targets) fieldConflicts(block, model, mixins, comparison, conflicts);
424
+ for (const block of added) modelConflicts(block, allDeclared, comparison, conflicts);
425
+ const { aheadOfEmit, storedUnderAnotherName } = conflicts;
426
+ if (aheadOfEmit.length > 0) throw notChanged(comparison, `${listOf([...new Set(aheadOfEmit.map(({ path }) => path))])} already declares ${listOf(aheadOfEmitNames(aheadOfEmit))}, which the emitted contract does not have. Run \`prisma contract emit\`, then update your database.`);
427
+ if (storedUnderAnotherName.length > 0) throw notChanged(comparison, storedUnderAnotherName.map(storedUnderAnotherNameReason).join(" "));
428
+ const newNamespace = comparison.namespace ?? comparison.defaultNamespace;
429
+ for (const block of added) {
430
+ const other = others.find(({ namespaceId, name }) => namespaceId === newNamespace && name === block.modelName);
431
+ if (other === void 0) continue;
432
+ throw notChanged(comparison, `${other.path} declares the ${other.kind} ${other.name}, and Better Auth's model ${block.physicalName ?? block.modelName} needs that name. Rename the ${other.kind}, then run \`auth generate\` again.`);
433
+ }
434
+ const touched = uniquePaths(targets);
435
+ if (touched.length > 1) throw notChanged(comparison, `the additions belong in ${listOf(touched)}, and Better Auth writes one file. Add them by hand.`);
436
+ const file = targets[0]?.file ?? files[0];
437
+ if (file === void 0) throw notChanged(comparison, "no contract file was found.");
438
+ const eol = file.text.includes("\r\n") ? "\r\n" : "\n";
439
+ const unit = indentUnit(file.text, [...declared.values()].flat().filter((model) => model.file === file));
440
+ const insertions = targets.map(({ block, declaration }) => {
441
+ const insertion = fieldInsertion(file.text, declaration, block, eol, unit);
442
+ if (insertion === void 0) throw notChanged(comparison, `model ${block.modelName} is written on one line. Put its \`}\` on a line of its own and run \`auth generate\` again.`);
443
+ return insertion;
444
+ });
445
+ if (added.length > 0) {
446
+ const models = reindented(renderBlocks(added, comparison.namespace), unit).split("\n").join(eol);
447
+ insertions.push({
448
+ offset: file.text.length,
449
+ text: `${separatorBefore(file.text, eol)}${models}${eol}`
450
+ });
451
+ }
452
+ let code = file.text;
453
+ for (const { offset, text } of [...insertions].sort((a, b) => b.offset - a.offset)) code = `${code.slice(0, offset)}${text}${code.slice(offset)}`;
454
+ const rejected = firstNewDiagnostic(files, files.map((candidate) => candidate === file ? {
455
+ path: file.path,
456
+ text: code
457
+ } : candidate), comparison.defaultNamespace, insertions.map(({ offset, text }) => ({
458
+ path: file.path,
459
+ offset,
460
+ length: text.length
461
+ })));
462
+ if (rejected !== void 0) throw notChanged(comparison, `Prisma would not accept the edited ${rejected.path}: ${rejected.message} (line ${rejected.line}).`);
463
+ return {
464
+ file,
465
+ code,
466
+ summary: summaryOf(file.path, extended, added, printed.notes)
467
+ };
468
+ }
469
+ //#endregion
470
+ //#region src/generate/edited-contract-source.ts
471
+ /**
472
+ * What `auth generate` writes when the contract lacks models or fields: the whole edited contract file at its absolute path, for Better Auth to overwrite after it asks. Prints what is added. Throws the contract message when the contract cannot be edited.
473
+ */
474
+ async function editedContractSource(file, comparison) {
475
+ assertOnlyAdditions(comparison);
476
+ const edit = editContractSource(await contractSourceFiles(file, comparison), comparison);
477
+ console.log(edit.summary);
478
+ return {
479
+ code: edit.code,
480
+ path: edit.file.absolutePath,
481
+ overwrite: true
482
+ };
483
+ }
484
+ //#endregion
485
+ export { editedContractSource };
486
+
487
+ //# sourceMappingURL=edited-contract-source-uFJmCt41.mjs.map