import { AnyNull, AnyNullClass, DbNull, DbNullClass, JsonArray, JsonNull, JsonNullClass, JsonNullValues, JsonObject, JsonValue } from "./common-types.cjs"; import * as _$kysely from "kysely"; import { AddColumnNode, AddConstraintNode, AddIndexNode, AddValueNode, AggregateFunctionNode, AliasNode, AliasableExpression, AlterColumnNode, AlterTableNode, AlterTypeNode, AndNode, BinaryOperationNode, CaseNode, CastNode, CheckConstraintNode, CollateNode, ColumnDefinitionNode, ColumnNode, ColumnUpdateNode, CommonTableExpressionNameNode, CommonTableExpressionNode, CreateIndexNode, CreateSchemaNode, CreateTableNode, CreateTypeNode, CreateViewNode, DataTypeNode, DefaultInsertValueNode, DefaultValueNode, DeleteQueryNode, Dialect, DropColumnNode, DropConstraintNode, DropIndexNode, DropSchemaNode, DropTableNode, DropTypeNode, DropViewNode, ExplainNode, Expression, ExpressionBuilder, ExpressionWrapper, FetchNode, ForeignKeyConstraintNode, FromNode, FunctionNode, Generated, GeneratedNode, GroupByItemNode, GroupByNode, HavingNode, IdentifierNode, InsertQueryNode, JSONOperatorChainNode, JSONPathLegNode, JSONPathNode, JSONReferenceNode, JoinNode, Kysely, KyselyConfig, LimitNode, ListNode, MatchedNode, MergeQueryNode, ModifyColumnNode, OffsetNode, OnConflictNode, OnDuplicateKeyNode, OnNode, OperandExpression, OperationNode, OperationNodeVisitor, OperatorNode, OrActionNode, OrNode, OrderByItemNode, OrderByNode, OutputNode, OverNode, ParensNode, PartitionByItemNode, PartitionByNode, PrimaryKeyConstraintNode, PrimitiveValueListNode, QueryId, QueryResult, RawNode, ReferenceNode, ReferencesNode, RefreshMaterializedViewNode, RenameColumnNode, RenameConstraintNode, RenameValueNode, ReturningNode, RootOperationNode, SchemableIdentifierNode, SelectAllNode, SelectModifierNode, SelectQueryBuilder, SelectQueryNode, SelectionNode, SetOperationNode, SqlBool, TableNode, TopNode, TupleNode, UnaryOperationNode, UniqueConstraintNode, UnknownRow, UpdateQueryNode, UsingNode, ValueListNode, ValueNode, ValuesNode, WhenNode, WhereNode, WithNode } from "kysely"; import * as _$_zenstackhq_schema0 from "@zenstackhq/schema"; import { ArrayExpression, BinaryExpression, BindingExpression, BuiltinType, CallExpression, DataSourceProviderType, Expression as Expression$1, FieldDef, FieldExpression, FieldHasDefault, FieldIsArray, FieldIsDelegateDiscriminator, FieldIsRelation, FieldType, ForeignKeyFields, GetEnum, GetEnums, GetModel, GetModelDelegateMapValue, GetModelDiscriminator, GetModelField, GetModelFieldType, GetModelFields, GetModels, GetSubModels, GetTypeDefField, GetTypeDefFieldType, GetTypeDefFields, GetTypeDefs, IsDelegateModel, LiteralExpression, MemberExpression, ModelDef, ModelFieldIsOptional, NonRelationFields, NullExpression, ProcedureDef, RelationFieldType, RelationFields, RelationInfo, ScalarFields, SchemaDef, ThisExpression, TypeDefFieldIsArray, TypeDefFieldIsOptional, UnaryExpression, UpdatedAtInfo } from "@zenstackhq/schema"; import { ZodType, z } from "zod"; import Decimal from "decimal.js"; //#region \0rolldown/runtime.js declare namespace kysely_utils_d_exports { export { AnyKysely, DefaultOperationNodeVisitor }; } declare class DefaultOperationNodeVisitor extends OperationNodeVisitor { protected defaultVisit(node: OperationNode): void; protected visitSelectQuery(node: SelectQueryNode): void; protected visitSelection(node: SelectionNode): void; protected visitColumn(node: ColumnNode): void; protected visitAlias(node: AliasNode): void; protected visitTable(node: TableNode): void; protected visitFrom(node: FromNode): void; protected visitReference(node: ReferenceNode): void; protected visitAnd(node: AndNode): void; protected visitOr(node: OrNode): void; protected visitValueList(node: ValueListNode): void; protected visitParens(node: ParensNode): void; protected visitJoin(node: JoinNode): void; protected visitRaw(node: RawNode): void; protected visitWhere(node: WhereNode): void; protected visitInsertQuery(node: InsertQueryNode): void; protected visitDeleteQuery(node: DeleteQueryNode): void; protected visitReturning(node: ReturningNode): void; protected visitCreateTable(node: CreateTableNode): void; protected visitAddColumn(node: AddColumnNode): void; protected visitColumnDefinition(node: ColumnDefinitionNode): void; protected visitDropTable(node: DropTableNode): void; protected visitOrderBy(node: OrderByNode): void; protected visitOrderByItem(node: OrderByItemNode): void; protected visitGroupBy(node: GroupByNode): void; protected visitGroupByItem(node: GroupByItemNode): void; protected visitUpdateQuery(node: UpdateQueryNode): void; protected visitColumnUpdate(node: ColumnUpdateNode): void; protected visitLimit(node: LimitNode): void; protected visitOffset(node: OffsetNode): void; protected visitOnConflict(node: OnConflictNode): void; protected visitOnDuplicateKey(node: OnDuplicateKeyNode): void; protected visitCheckConstraint(node: CheckConstraintNode): void; protected visitDataType(node: DataTypeNode): void; protected visitSelectAll(node: SelectAllNode): void; protected visitIdentifier(node: IdentifierNode): void; protected visitSchemableIdentifier(node: SchemableIdentifierNode): void; protected visitValue(node: ValueNode): void; protected visitPrimitiveValueList(node: PrimitiveValueListNode): void; protected visitOperator(node: OperatorNode): void; protected visitCreateIndex(node: CreateIndexNode): void; protected visitDropIndex(node: DropIndexNode): void; protected visitList(node: ListNode): void; protected visitPrimaryKeyConstraint(node: PrimaryKeyConstraintNode): void; protected visitUniqueConstraint(node: UniqueConstraintNode): void; protected visitReferences(node: ReferencesNode): void; protected visitWith(node: WithNode): void; protected visitCommonTableExpression(node: CommonTableExpressionNode): void; protected visitCommonTableExpressionName(node: CommonTableExpressionNameNode): void; protected visitHaving(node: HavingNode): void; protected visitCreateSchema(node: CreateSchemaNode): void; protected visitDropSchema(node: DropSchemaNode): void; protected visitAlterTable(node: AlterTableNode): void; protected visitDropColumn(node: DropColumnNode): void; protected visitRenameColumn(node: RenameColumnNode): void; protected visitAlterColumn(node: AlterColumnNode): void; protected visitModifyColumn(node: ModifyColumnNode): void; protected visitAddConstraint(node: AddConstraintNode): void; protected visitDropConstraint(node: DropConstraintNode): void; protected visitForeignKeyConstraint(node: ForeignKeyConstraintNode): void; protected visitCreateView(node: CreateViewNode): void; protected visitDropView(node: DropViewNode): void; protected visitGenerated(node: GeneratedNode): void; protected visitDefaultValue(node: DefaultValueNode): void; protected visitOn(node: OnNode): void; protected visitValues(node: ValuesNode): void; protected visitSelectModifier(node: SelectModifierNode): void; protected visitCreateType(node: CreateTypeNode): void; protected visitDropType(node: DropTypeNode): void; protected visitExplain(node: ExplainNode): void; protected visitDefaultInsertValue(node: DefaultInsertValueNode): void; protected visitAggregateFunction(node: AggregateFunctionNode): void; protected visitOver(node: OverNode): void; protected visitPartitionBy(node: PartitionByNode): void; protected visitPartitionByItem(node: PartitionByItemNode): void; protected visitSetOperation(node: SetOperationNode): void; protected visitBinaryOperation(node: BinaryOperationNode): void; protected visitUnaryOperation(node: UnaryOperationNode): void; protected visitUsing(node: UsingNode): void; protected visitFunction(node: FunctionNode): void; protected visitCase(node: CaseNode): void; protected visitWhen(node: WhenNode): void; protected visitJSONReference(node: JSONReferenceNode): void; protected visitJSONPath(node: JSONPathNode): void; protected visitJSONPathLeg(node: JSONPathLegNode): void; protected visitJSONOperatorChain(node: JSONOperatorChainNode): void; protected visitTuple(node: TupleNode): void; protected visitMergeQuery(node: MergeQueryNode): void; protected visitMatched(node: MatchedNode): void; protected visitAddIndex(node: AddIndexNode): void; protected visitCast(node: CastNode): void; protected visitFetch(node: FetchNode): void; protected visitTop(node: TopNode): void; protected visitOutput(node: OutputNode): void; protected visitRenameConstraint(node: RenameConstraintNode): void; protected visitRefreshMaterializedView(node: RefreshMaterializedViewNode): void; protected visitOrAction(node: OrActionNode): void; protected visitCollate(node: CollateNode): void; protected visitAlterType(node: AlterTypeNode): void; protected visitAddValue(node: AddValueNode): void; protected visitRenameValue(node: RenameValueNode): void; } type AnyKysely = Kysely; //#endregion //#region src/utils/type-utils.d.ts type Optional = Omit & Partial>; type PartialIf = Condition extends true ? Partial : T; type NullableIf = Condition extends true ? T | null : T; type _Preserve = Date | Function | Decimal | Uint8Array | JsonObject | JsonValue; type _Depth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; type Simplify = D extends 0 ? T : T extends object ? T extends _Preserve ? T : { [K in keyof T]: Simplify } & {} : T; type WrapType = Array extends true ? Optional extends true ? T[] | null : T[] : Optional extends true ? T | null : T; type TypeMap = { String: string; Boolean: boolean; Int: number; Float: number; BigInt: bigint; Decimal: Decimal; DateTime: Date; Bytes: Uint8Array; Json: JsonValue | null; Null: null; Object: Record; Any: unknown; Unsupported: unknown; Void: void; Undefined: undefined; }; type MapBaseType$1 = T extends keyof TypeMap ? TypeMap[T] : unknown; type OrArray = IF extends true ? T | T[] : T; type NonEmptyArray = [T, ...T[]]; type ValueOfPotentialTuple = T extends unknown[] ? T[number] : T; type NoExpand = T extends unknown ? T : never; type AtLeast = NoExpand; type Without = { [P in Exclude]?: never }; type XOR = T extends object ? (U extends object ? (Without & U) | (Without & T) : U) : T; type MaybePromise = T | Promise; type OrUndefinedIf = Condition extends true ? T | undefined : T; type UnwrapTuplePromises = { [K in keyof T]: Awaited }; //#endregion //#region src/client/constants.d.ts /** * Client API methods that are not supported in transactions. */ declare const TRANSACTION_UNSUPPORTED_METHODS: readonly ["$transaction", "$connect", "$disconnect", "$use"]; /** * Logical combinators used in filters. */ declare const LOGICAL_COMBINATORS: readonly ["AND", "OR", "NOT"]; /** * Aggregation operators. */ declare const AggregateOperators: readonly ["_count", "_sum", "_avg", "_min", "_max"]; type AggregateOperators = (typeof AggregateOperators)[number]; /** * Mapping of filter operators to their corresponding filter kind categories. */ declare const FILTER_PROPERTY_TO_KIND: { readonly equals: "Equality"; readonly not: "Equality"; readonly in: "Equality"; readonly notIn: "Equality"; readonly lt: "Range"; readonly lte: "Range"; readonly gt: "Range"; readonly gte: "Range"; readonly between: "Range"; readonly contains: "Like"; readonly startsWith: "Like"; readonly endsWith: "Like"; readonly mode: "Like"; readonly is: "Relation"; readonly isNot: "Relation"; readonly some: "Relation"; readonly every: "Relation"; readonly none: "Relation"; readonly path: "Json"; readonly string_contains: "Json"; readonly string_starts_with: "Json"; readonly string_ends_with: "Json"; readonly array_contains: "Json"; readonly array_starts_with: "Json"; readonly array_ends_with: "Json"; readonly fuzzy: "Fuzzy"; readonly fts: "FullText"; readonly has: "List"; readonly hasEvery: "List"; readonly hasSome: "List"; readonly isEmpty: "List"; }; /** * Mapping of filter operators to their corresponding filter kind categories. */ type FilterPropertyToKind = typeof FILTER_PROPERTY_TO_KIND; //#endregion //#region src/client/query-builder.d.ts type ToKyselySchema = { [Model in GetModels]: ToKyselyTable }; type ToKysely = Kysely>; type ToKyselyTable> = { [Field in ScalarFields | ForeignKeyFields as GetModelField['originModel'] extends string ? never : Field]: toKyselyFieldType }; type MapBaseType = T extends 'String' ? string : T extends 'Boolean' ? boolean : T extends 'Int' | 'Float' ? number : T extends 'BigInt' ? bigint : T extends 'Decimal' ? Decimal : T extends 'DateTime' ? string : unknown; type WrapNull = Null extends true ? T | null : T; type MapType$1, Field extends GetModelFields> = WrapNull>, ModelFieldIsOptional>; type toKyselyFieldType, Field extends GetModelFields> = FieldHasDefault extends true ? Generated> : MapType$1; //#endregion //#region src/client/plugin.d.ts type AllowedExtQueryArgKeys = CoreCrudOperations | '$create' | '$read' | '$update' | '$delete' | '$all'; /** * Base shape of plugin-extended query args. */ type ExtQueryArgsBase = { [K in AllowedExtQueryArgKeys]?: object }; /** * Base type for plugin-extended client members (methods and properties). * Member names should start with '$' to avoid model name conflicts. */ type ExtClientMembersBase = Record; /** * Base shape of plugin-extended result fields. * Keyed by model name, each value maps field names to their definitions. * `needs` keys are constrained to non-relation fields of the corresponding model. */ type ExtResultBase = { [M in GetModels as Uncapitalize]?: Record, true>>; compute: (...args: any[]) => any; }> }; /** * Mapped type that provides per-field contextual typing for `compute` callbacks * based on the `needs` declaration. Uses a separate type parameter `R_` that captures * the needs shape (model → field → { neededField: true }), then links each field's * `compute` parameter to exactly the keys declared in its `needs`. */ type ExtResultInferenceArgs = { [K in keyof R_ & string]: { [P in keyof R_[K]]?: { needs?: { [F in keyof R_[K][P]]: F extends NonRelationFields> ? true : never } & Partial>, true>>; compute: (data: ExtResultComputeData, R_[K][P]>) => unknown; } } }; /** * Reverse-maps an uncapitalized key back to the original model name in the schema. * E.g., for a schema with model `myModel`, the key `myModel` maps back to `myModel` * (not `MyModel` as `Capitalize` would produce). */ type ModelNameFromKey = { [M in GetModels]: Uncapitalize extends K ? M : never }[GetModels]; /** * Maps the needs shape `S` to an object with actual schema field types. * For each key in `S` that is a valid non-relation field of model `M`, * resolves the TypeScript type from the schema field definition. */ type ExtResultComputeData, S> = { [F in keyof S & GetModelFields]: MapModelFieldType }; /** * ZenStack runtime plugin. */ interface RuntimePlugin, ExtResult extends ExtResultBase> { /** * Plugin ID. */ id: string; /** * Plugin display name. */ name?: string; /** * Plugin description. */ description?: string; /** * Custom function implementations. * @private */ functions?: Record>; /** * Intercepts an ORM query. */ onQuery?: OnQueryCallback; /** * Intercepts a procedure invocation. */ onProcedure?: OnProcedureCallback; /** * Intercepts an entity mutation. */ onEntityMutation?: EntityMutationHooksDef; /** * Intercepts a Kysely query. */ onKyselyQuery?: OnKyselyQueryCallback; /** * Extended query args configuration. */ queryArgs?: { [K in keyof ExtQueryArgs]: ZodType }; /** * Extended client members (methods and properties). */ client?: ExtClientMembers; /** * Extended result fields on query results. * Keyed by model name, each value defines computed fields with `needs` and `compute`. */ result?: ExtResult; } type AnyPlugin = RuntimePlugin; /** * Defines a ZenStack runtime plugin based on type of the given schema. * * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation} * * @example * ```typescript * definePlugin(schema, { * id: 'my-plugin', * result: { * user: { * fullName: { * needs: { firstName: true, lastName: true }, * compute: (user) => `${user.firstName} ${user.lastName}`, * }, * }, * }, * }); * ``` */ declare function definePlugin = {}, const ExtResult extends ExtResultBase = {}, R_ = {}>(schema: Schema, plugin: RuntimePlugin & { result?: ExtResultInferenceArgs; }): RuntimePlugin; /** * Defines a ZenStack runtime plugin. * * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation} * * @example * ```typescript * definePlugin(schema, { * id: 'my-plugin', * result: { * user: { * fullName: { * needs: { firstName: true, lastName: true }, * compute: (user) => `${user.firstName} ${user.lastName}`, * }, * }, * }, * }); * ``` * */ declare function definePlugin = {}, const ExtResult extends ExtResultBase = {}>(plugin: RuntimePlugin): RuntimePlugin; type OnProcedureCallback = (ctx: OnProcedureHookContext) => Promise; type OnProcedureHookContext = { /** * The procedure name. */ name: string; /** * Whether the procedure is a mutation. */ mutation: boolean; /** * Procedure invocation input (envelope). * * The canonical shape is `{ args?: Record }`. * When a procedure has required params, `args` is required. */ input: unknown; /** * Continues the invocation. The input passed here is forwarded to the next handler. */ proceed: (input: unknown) => Promise; /** * The ZenStack client that is invoking the procedure. */ client: ClientContract; }; type OnQueryCallback = (ctx: OnQueryHookContext) => Promise; type OnQueryHookContext = { /** * The model that is being queried. */ model: GetModels; /** * The operation that is being performed. */ operation: AllCrudOperations; /** * The query arguments. */ args: Record | undefined; /** * The function to proceed with the original query. * It takes the same arguments as the operation method. * * @param args The query arguments. */ proceed: (args: Record | undefined) => Promise; /** * The ZenStack client that is performing the operation. */ client: ClientContract; }; type EntityMutationHooksDef = { /** * Called before entities are mutated. */ beforeEntityMutation?: BeforeEntityMutationCallback; /** * Called after entities are mutated. */ afterEntityMutation?: AfterEntityMutationCallback; /** * Whether to run after-mutation hooks within the transaction that performs the mutation. * * If set to `true`, if the mutation already runs inside a transaction, the callbacks are * executed immediately after the mutation within the transaction boundary. If the mutation * is not running inside a transaction, a new transaction is created to run both the mutation * and the callbacks. * * If set to `false`, the callbacks are executed after the mutation transaction is committed. * * Defaults to `false`. */ runAfterMutationWithinTransaction?: boolean; }; type MutationHooksArgs = { /** * The model that is being mutated. */ model: GetModels; /** * The mutation action that is being performed. */ action: 'create' | 'update' | 'delete'; /** * The mutation data. Only available for create and update actions. */ queryNode: OperationNode; /** * A query ID that uniquely identifies the mutation operation. You can use it to correlate * data between the before and after mutation hooks. */ queryId: QueryId; }; type BeforeEntityMutationCallback = (args: PluginBeforeEntityMutationArgs) => MaybePromise; type AfterEntityMutationCallback = (args: PluginAfterEntityMutationArgs) => MaybePromise; type PluginBeforeEntityMutationArgs = MutationHooksArgs & { /** * Loads the entities that are about to be mutated. The db operation that loads the entities is executed * within the same transaction context as the mutation. */ loadBeforeMutationEntities(): Promise[] | undefined>; /** * The ZenStack client you can use to perform additional operations. The database operations initiated * from this client are executed within the same transaction as the mutation if the mutation is running * inside a transaction. * * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops. */ client: ClientContract; }; type PluginAfterEntityMutationArgs = MutationHooksArgs & { /** * Loads the entities that have been mutated. */ loadAfterMutationEntities(): Promise[] | undefined>; /** * The entities before mutation. Only available if `beforeEntityMutation` hook is provided and * the `loadBeforeMutationEntities` function is called in that hook. */ beforeMutationEntities?: Record[]; /** * The ZenStack client you can use to perform additional operations. * See {@link EntityMutationHooksDef.runAfterMutationWithinTransaction} for detailed transaction behavior. * * Mutations initiated from this client will NOT trigger entity mutation hooks to avoid infinite loops. */ client: ClientContract; }; type OnKyselyQueryArgs = { schema: SchemaDef; client: ClientContract; query: RootOperationNode; proceed: ProceedKyselyQueryFunction; }; type ProceedKyselyQueryFunction = (query: RootOperationNode) => Promise>; type OnKyselyQueryCallback = (args: OnKyselyQueryArgs) => Promise>; //#endregion //#region src/client/options.d.ts type ZModelFunctionContext = { /** * ZenStack client instance */ client: ClientContract; /** * Database dialect */ dialect: BaseCrudDialect; /** * The containing model name */ model: GetModels; /** * The alias name that can be used to refer to the containing model */ modelAlias: string; /** * The CRUD operation being performed */ operation: CRUD_EXT; }; type ZModelFunction = (eb: ExpressionBuilder, keyof ToKyselySchema>, args: Expression[], context: ZModelFunctionContext) => Expression; /** * Options for slicing ORM client's capabilities by including/excluding certain models, operations, * filters, etc. */ type SlicingOptions = { /** * Models to include in the client. If not specified, all models are included by default. */ includedModels?: readonly GetModels[]; /** * Models to exclude from the client. Exclusion takes precedence over inclusion. */ excludedModels?: readonly GetModels[]; /** * Model slicing options. */ models?: { [Model in GetModels as Uncapitalize]?: ModelSlicingOptions } & { /** * Slicing options that apply to all models. Model-specific options will override these general * options if both are specified. */ $all?: ModelSlicingOptions>; }; /** * Procedures to include in the client. If not specified, all procedures are included by default. */ includedProcedures?: readonly GetProcedureNames[]; /** * Procedures to exclude from the client. Exclusion takes precedence over inclusion. */ excludedProcedures?: readonly GetProcedureNames[]; }; /** * Kinds of filter operations. */ type FilterKind = FilterPropertyToKind[keyof FilterPropertyToKind]; /** * Model slicing options. */ type ModelSlicingOptions> = { /** * ORM query operations to include for the model. If not specified, all operations are included * by default. */ includedOperations?: readonly AllCrudOperations[]; /** * ORM query operations to exclude for the model. Exclusion takes precedence over inclusion. */ excludedOperations?: readonly AllCrudOperations[]; /** * Field-level slicing options. */ fields?: { [Field in GetModelFields]?: FieldSlicingOptions } & { /** * Field slicing options that apply to all fields. Field-specific options will override these * general options if both are specified. */ $all?: FieldSlicingOptions; }; }; /** * Field slicing options. */ type FieldSlicingOptions = { /** * Filter kinds to include for the field. If not specified, all filter kinds are included by default. */ includedFilterKinds?: readonly FilterKind[]; /** * Filter kinds to exclude for the field. Exclusion takes precedence over inclusion. */ excludedFilterKinds?: readonly FilterKind[]; }; /** * Partial ORM client options that defines customizable behaviors. */ type QueryOptions = { /** * Options for omitting fields in ORM query results. */ omit?: OmitConfig; /** * Whether to allow overriding omit settings at query time. Defaults to `true`. When set to `false`, a * query-time `omit` clause that sets the field to `false` (not omitting) will trigger a validation error. */ allowQueryTimeOmitOverride?: boolean; /** * Options for slicing ORM client's capabilities by including/excluding certain models, operations, filters, etc. */ slicing?: SlicingOptions; }; /** * Projects a (typically inferred) client options type down to only the members that influence * ORM typing - the {@link QueryOptions} fields (`omit`, `allowQueryTimeOmitOverride`, `slicing`). * * The full options object inferred at `new ZenStackClient(...)` carries heavy function types for * `computedFields` and `procedures`. Those are never read by the model/operation types, but if the * raw options type is fanned out across every model's `ModelOperations` instantiation (30+ for a * typical schema) it inflates type checking dramatically. Projecting to the query-relevant subset * before the fan-out keeps the per-model types cheap while preserving full options on `$options`. */ type QueryRelevantOptions = Pick>>; /** * ZenStack client options. */ type ClientOptions = QueryOptions & { /** * Kysely dialect. */ dialect: Dialect; /** * Custom function definitions. * * @private */ functions?: Record>; /** * Plugins. */ plugins?: AnyPlugin[]; /** * Logging configuration. Extends Kysely's log config with a `'warning'` level * for ZenStack-specific diagnostics (e.g., slow query warnings). */ log?: KyselyConfig['log']; /** * Whether to automatically fix timezone for `DateTime` fields returned by node-pg. Defaults * to `true`. * * Node-pg has a terrible quirk that it interprets the date value as local timezone (as a * `Date` object) although for `DateTime` field the data in DB is stored in UTC. * @see https://github.com/brianc/node-postgres/issues/429 */ fixPostgresTimezone?: boolean; /** * Whether to enable query args validation. Defaults to `true`. * * **USE WITH CAUTION**, as setting it to `false` will allow malformed input to pass through, causing * incorrect SQL generation or runtime errors. If you use validation attributes like `@email`, `@regex`, * etc., in ZModel, they will be ignored too. */ validateInput?: boolean; /** * Whether to use compact alias names (e.g., "$$t1", "$$t2") when transforming ORM queries to SQL. * Defaults to `true`. * * When set to `false`, original aliases are kept unless temporary aliases become too long for * safe SQL identifier handling, in which case compact aliases are used as a fallback. */ useCompactAliasNames?: boolean; /** * Whether to skip validation for whether all computed fields are properly defined. */ skipValidationForComputedFields?: boolean; /** * Diagnostics related options. */ diagnostics?: { /** * Threshold in milliseconds for determining slow queries. If not specified, no query will be considered slow. */ slowQueryThresholdMs?: number; /** * Maximum number of slow query records to keep in memory. Defaults to `100`. When the number is exceeded, the * entry with the lowest duration will be removed. Set to `Infinity` to keep unlimited records. */ slowQueryMaxRecords?: number; }; } & (HasComputedFields extends true ? { /** * Computed field definitions. */ computedFields: ComputedFieldsOptions; } : {}) & (HasProcedures extends true ? { /** * Custom procedure definitions. */ procedures: ProceduresOptions; } : {}); /** * Config for omitting fields in ORM query results. */ type OmitConfig = { [Model in GetModels as Uncapitalize]?: { [Field in GetModelFields as Field extends ScalarFields ? Field : never]?: boolean } }; type ComputedFieldsOptions = { [Model in GetModels as 'computedFields' extends keyof GetModel ? Uncapitalize : never]: { [Field in keyof Schema['models'][Model]['computedFields']]: Schema['models'][Model]['computedFields'][Field] extends infer Func ? Func extends ((...args: any[]) => infer R) ? (p: ExpressionBuilder, Model>, ...args: Parameters) => OperandExpression : never : never } }; type HasComputedFields = string extends GetModels ? false : keyof ComputedFieldsOptions extends never ? false : true; type ProceduresOptions = Schema extends { procedures: Record; } ? { [Key in GetProcedureNames]: ProcedureHandlerFunc } : {}; type HasProcedures = Schema extends { procedures: Record; } ? true : false; /** * Extracts QueryOptions from an object with '$options' property. */ type GetQueryOptions = T['$options']; //#endregion //#region src/client/crud/dialects/base-dialect.d.ts declare abstract class BaseCrudDialect { protected readonly schema: Schema; protected readonly options: ClientOptions; protected eb: ExpressionBuilder; constructor(schema: Schema, options: ClientOptions); /** * Whether the dialect supports updating with a limit on the number of updated rows. */ abstract get supportsUpdateWithLimit(): boolean; /** * Whether the dialect supports deleting with a limit on the number of deleted rows. */ abstract get supportsDeleteWithLimit(): boolean; /** * Whether the dialect supports DISTINCT ON. */ abstract get supportsDistinctOn(): boolean; /** * Whether the dialect support inserting with `DEFAULT` as field value. */ abstract get supportsDefaultAsFieldValue(): boolean; /** * Whether the dialect supports the RETURNING clause in INSERT/UPDATE/DELETE statements. */ abstract get supportsReturning(): boolean; /** * Whether the dialect supports `INSERT INTO ... DEFAULT VALUES` syntax. */ abstract get supportsInsertDefaultValues(): boolean; /** * How to perform insert ignore operation. */ abstract get insertIgnoreMethod(): 'onConflict' | 'ignore'; /** * Transforms input value before sending to database. * * `fieldDef` is optional so existing callers that don't have it stay * source-compatible. Dialects can use it to inspect `@db.*` native-type * attributes (e.g. to format `@db.Time` values as `HH:MM:SS` rather than * full ISO timestamps). */ transformInput(value: unknown, _type: BuiltinType, _forArrayField: boolean, _fieldDef?: FieldDef): unknown; /** * Transforms output value received from database. */ transformOutput(value: unknown, _type: BuiltinType, _array: boolean): unknown; buildSelectModel(model: string, modelAlias: string): SelectQueryBuilder; buildFilterSortTake(model: string, args: FindArgs, any, true>, query: SelectQueryBuilder, modelAlias: string): SelectQueryBuilder; buildFilter(model: string, modelAlias: string, where: boolean | object | undefined): Expression; private buildCursorFilter; private isLogicalCombinator; protected buildCompositeFilter(model: string, modelAlias: string, key: (typeof LOGICAL_COMBINATORS)[number], payload: any): Expression; private buildRelationFilter; private buildToOneRelationFilter; private buildToManyRelationFilter; private buildArrayFilter; buildPrimitiveFilter(fieldRef: Expression, fieldDef: FieldDef, payload: any): any; private buildJsonFilter; private buildPlainJsonFilter; private buildTypedJsonFilter; private buildTypedJsonArrayFilter; private buildTypeJsonNonArrayFilter; private buildJsonValueFilterClause; protected buildJsonEqualityFilter(lhs: Expression, rhs: unknown): Expression; private buildValueFilter; private buildStandardFilter; private buildStringFilter; private buildJsonStringFilter; private escapeLikePattern; private buildStringLike; private prepStringCasing; private buildNumberFilter; private buildBooleanFilter; private buildDateTimeFilter; private buildBytesFilter; private buildEnumFilter; buildOrderBy(query: SelectQueryBuilder, model: string, modelAlias: string, orderBy: OrArray, boolean, boolean>> | undefined, negated: boolean, take: number | undefined): SelectQueryBuilder; private applyRelationOrderBy; private applyScalarOrderBy; private applyAggregationOrderBy; private applyFuzzyRelevanceOrderBy; private applyFtsRelevanceOrderBy; buildSelectAllFields(model: string, query: SelectQueryBuilder, omit: Record | undefined | null, modelAlias: string): SelectQueryBuilder; shouldOmitField(omit: unknown, model: string, field: string): any; protected buildModelSelect(model: GetModels, subQueryAlias: string, payload: true | FindArgs, any, true>, selectAllFields: boolean): SelectQueryBuilder; buildSelectField(query: SelectQueryBuilder, model: string, modelAlias: string, field: string): SelectQueryBuilder; buildDelegateJoin(thisModel: string, thisModelAlias: string, otherModelAlias: string, query: SelectQueryBuilder): SelectQueryBuilder; buildCountJson(model: string, eb: ExpressionBuilder, parentAlias: string, payload: any): AliasableExpression; protected negateSort(sort: SortOrder, negated: boolean): SortOrder; true(): Expression; false(): Expression; isTrue(expression: Expression): boolean; isFalse(expression: Expression): boolean; and(...args: Expression[]): Expression; or(...args: Expression[]): Expression; not(...args: Expression[]): ExpressionWrapper; fieldRef(model: string, field: string, modelAlias?: string, inlineComputedField?: boolean): any; protected canJoinWithoutNestedSelect(modelDef: ModelDef, payload: boolean | FindArgs, any, true>): boolean; /** * Builds an EXISTS expression from an inner SELECT query. * Can be overridden by dialects that need special handling (e.g., MySQL wraps * in a derived table to avoid "can't specify target table for update in FROM clause"). */ protected buildExistsExpression(innerQuery: SelectQueryBuilder): Expression; abstract get provider(): DataSourceProviderType; /** * Builds selection for a relation field. */ abstract buildRelationSelection(query: SelectQueryBuilder, model: string, relationField: string, parentAlias: string, payload: true | FindArgs, any, true>): SelectQueryBuilder; /** * Builds skip and take clauses. */ abstract buildSkipTake(query: SelectQueryBuilder, skip: number | undefined, take: number | undefined): SelectQueryBuilder; /** * Builds an Kysely expression that returns a JSON object for the given key-value pairs. */ abstract buildJsonObject(value: Record>): AliasableExpression; /** * Builds an Kysely expression that returns the length of an array. */ abstract buildArrayLength(array: Expression): AliasableExpression; /** * Builds an array value expression. */ abstract buildArrayValue(values: Expression[], elemType: string): AliasableExpression; /** * Builds an expression that checks if an array contains a single value. */ abstract buildArrayContains(field: Expression, value: Expression, elemType?: string): AliasableExpression; /** * Builds an expression that checks if an array contains all values from another array. */ abstract buildArrayHasEvery(field: Expression, values: Expression): AliasableExpression; /** * Builds an expression that checks if an array overlaps with another array. */ abstract buildArrayHasSome(field: Expression, values: Expression): AliasableExpression; /** * Casts the given expression to an integer type. */ abstract castInt>(expression: T): T; /** * Casts the given expression to a text type. */ abstract castText>(expression: T): T; /** * Trims double quotes from the start and end of a text expression. */ abstract trimTextQuotes>(expression: T): T; abstract getStringCasingBehavior(): { supportsILike: boolean; likeCaseSensitive: boolean; }; /** * Builds a VALUES table and select all fields from it. */ abstract buildValuesTableSelect(fields: FieldDef[], rows: unknown[][]): SelectQueryBuilder; /** * Builds a binary comparison expression between two operands. */ buildComparison(left: Expression, _leftFieldDef: FieldDef | undefined, op: string, right: Expression, _rightFieldDef: FieldDef | undefined): Expression; /** * Builds a JSON path selection expression. */ protected abstract buildJsonPathSelection(receiver: Expression, path: string | undefined): Expression; /** * Builds a JSON array filter expression. */ protected abstract buildJsonArrayFilter(receiver: Expression, operation: 'array_contains' | 'array_starts_with' | 'array_ends_with', value: unknown): Expression; /** * Builds a JSON array exists predicate (returning if any element matches the filter). */ protected abstract buildJsonArrayExistsPredicate(receiver: Expression, buildFilter: (elem: Expression) => Expression): Expression; /** * Builds an ORDER BY clause for a field with NULLS FIRST/LAST support. */ protected abstract buildOrderByField(query: SelectQueryBuilder, field: Expression, sort: SortOrder, nulls: 'first' | 'last'): SelectQueryBuilder; /** * Builds a fuzzy search filter for a string field using PostgreSQL `pg_trgm`. * The selected SQL form (operator vs. function, with/without `unaccent`) depends * on the resolved options. */ abstract buildFuzzyFilter(fieldRef: Expression, options: FuzzyFilterOptions): Expression; /** * Builds an ORDER BY clause that sorts by fuzzy relevance to a search term. */ abstract buildFuzzyRelevanceOrderBy(query: SelectQueryBuilder, fieldRefs: Expression[], search: string, sort: SortOrder, mode: FuzzyFilterOptions['mode'], unaccent: boolean): SelectQueryBuilder; /** * Validate the user-provided fuzzy filter payload and apply defaults so dialects * always receive a fully-resolved {@link FuzzyFilterOptions} value. */ protected normalizeFuzzyOptions(value: unknown): FuzzyFilterOptions; /** * Builds a full-text-search filter for a string field. Receives the raw * user-supplied filter payload — dialects validate/normalize it themselves * (the shape is provider-specific; only Postgres supports this filter). */ abstract buildFullTextFilter(fieldRef: Expression, payload: unknown): Expression; /** * Builds an ORDER BY clause that sorts by full-text-search relevance to a search term. */ abstract buildFtsRelevanceOrderBy(query: SelectQueryBuilder, fieldRefs: Expression[], search: string, config: string | undefined, sort: SortOrder): SelectQueryBuilder; } /** * Resolved options for a fuzzy filter passed to a dialect. `mode` and `unaccent` * are always populated (defaults: `mode='simple'`, `unaccent=false`, applied by * `normalizeFuzzyOptions`); `threshold` is optional and switches the SQL from * operator form (`%`, `<%`, `<<%`) to function form (`similarity() > threshold`). */ type FuzzyFilterOptions = { search: string; mode: 'simple' | 'word' | 'strictWord'; threshold?: number; unaccent: boolean; }; //#endregion //#region src/client/crud/validator/validator.d.ts type InputValidatorOptions = { /** * Whether validation is enabled. Defaults to `true`. */ enabled?: boolean; }; declare class InputValidator { private readonly client; readonly zodFactory: ZodSchemaFactory; private readonly enabled; constructor(client: ClientContract, options?: InputValidatorOptions); validateFindArgs(model: GetModels, args: unknown, operation: 'findFirst' | 'findUnique' | 'findMany'): FindArgs, any, true> | undefined; validateExistsArgs(model: GetModels, args: unknown): ExistsArgs, any> | undefined; validateCreateArgs(model: GetModels, args: unknown): CreateArgs, any>; validateCreateManyArgs(model: GetModels, args: unknown): CreateManyArgs>; validateCreateManyAndReturnArgs(model: GetModels, args: unknown): CreateManyAndReturnArgs, any> | undefined; validateUpdateArgs(model: GetModels, args: unknown): UpdateArgs, any>; validateUpdateManyArgs(model: GetModels, args: unknown): UpdateManyArgs, any>; validateUpdateManyAndReturnArgs(model: GetModels, args: unknown): UpdateManyAndReturnArgs, any>; validateUpsertArgs(model: GetModels, args: unknown): UpsertArgs, any>; validateDeleteArgs(model: GetModels, args: unknown): DeleteArgs, any>; validateDeleteManyArgs(model: GetModels, args: unknown): DeleteManyArgs, any> | undefined; validateCountArgs(model: GetModels, args: unknown): CountArgs, any> | undefined; validateAggregateArgs(model: GetModels, args: unknown): AggregateArgs, any>; validateGroupByArgs(model: GetModels, args: unknown): GroupByArgs, any>; validateProcedureInput(proc: string, input: unknown): unknown; private validate; } //#endregion //#region src/client/crud/operations/base.d.ts /** * List of core CRUD operations. It excludes the 'orThrow' variants. */ declare const CoreCrudOperations: readonly ["findMany", "findUnique", "findFirst", "create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany", "count", "aggregate", "groupBy", "exists"]; /** * List of core CRUD operations. It excludes the 'orThrow' variants. */ type CoreCrudOperations = (typeof CoreCrudOperations)[number]; /** * List of core read operations. It excludes the 'orThrow' variants. */ declare const CoreReadOperations: readonly ["findMany", "findUnique", "findFirst", "count", "aggregate", "groupBy", "exists"]; /** * List of core read operations. It excludes the 'orThrow' variants. */ type CoreReadOperations = (typeof CoreReadOperations)[number]; /** * List of core write operations. */ declare const CoreWriteOperations: readonly ["create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany"]; /** * List of core write operations. */ type CoreWriteOperations = (typeof CoreWriteOperations)[number]; /** * List of core create operations. */ declare const CoreCreateOperations: readonly ["create", "createMany", "createManyAndReturn", "upsert"]; /** * List of core create operations. */ type CoreCreateOperations = (typeof CoreCreateOperations)[number]; /** * List of core update operations. */ declare const CoreUpdateOperations: readonly ["update", "updateMany", "updateManyAndReturn", "upsert"]; /** * List of core update operations. */ type CoreUpdateOperations = (typeof CoreUpdateOperations)[number]; /** * List of core delete operations. */ declare const CoreDeleteOperations: readonly ["delete", "deleteMany"]; /** * List of core delete operations. */ type CoreDeleteOperations = (typeof CoreDeleteOperations)[number]; /** * List of all CRUD operations, including 'orThrow' variants. */ declare const AllCrudOperations: readonly ["findMany", "findUnique", "findFirst", "create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany", "count", "aggregate", "groupBy", "exists", "findUniqueOrThrow", "findFirstOrThrow"]; /** * List of all CRUD operations, including 'orThrow' variants. */ type AllCrudOperations = (typeof AllCrudOperations)[number]; /** * List of all read operations, including 'orThrow' variants. */ declare const AllReadOperations: readonly ["findMany", "findUnique", "findFirst", "count", "aggregate", "groupBy", "exists", "findUniqueOrThrow", "findFirstOrThrow"]; /** * List of all read operations, including 'orThrow' variants. */ type AllReadOperations = (typeof AllReadOperations)[number]; /** * List of all write operations - simply an alias of CoreWriteOperations. */ declare const AllWriteOperations: readonly ["create", "createMany", "createManyAndReturn", "update", "updateMany", "updateManyAndReturn", "upsert", "delete", "deleteMany"]; /** * List of all write operations - simply an alias of CoreWriteOperations. */ type AllWriteOperations = CoreWriteOperations; //#endregion //#region src/client/type-utils.d.ts /** * Checks if a model has any required Unsupported fields (non-optional, no default). * Uses raw field access since `GetModelFields` excludes Unsupported fields. */ type ModelHasRequiredUnsupportedField> = true extends { [Key in Extract['fields'], string>]: GetModel['fields'][Key] extends infer F extends FieldDef ? F['type'] extends 'Unsupported' ? F['optional'] extends true ? false : 'default' extends keyof F ? false : true : false : false }[Extract['fields'], string>] ? true : false; /** * Checks if a model allows create operations (not a delegate model and has no required Unsupported fields). */ type ModelAllowsCreate> = IsDelegateModel extends true ? false : ModelHasRequiredUnsupportedField extends true ? false : true; type IsNever = [T] extends [never] ? true : false; /** * Filters models based on slicing configuration. */ type GetSlicedModels> = Options['slicing'] extends infer S ? S extends SlicingOptions ? S['includedModels'] extends readonly GetModels[] ? Exclude>, S['excludedModels'] extends readonly GetModels[] ? S['excludedModels'][number] : never> : Exclude, S['excludedModels'] extends readonly GetModels[] ? S['excludedModels'][number] : never> : GetModels : GetModels; /** * Filters query operations based on slicing configuration for a specific model. */ type GetSlicedOperations, Options extends QueryOptions> = Options['slicing'] extends infer Slicing ? Slicing extends SlicingOptions ? GetIncludedOperations extends infer IO ? GetExcludedOperations extends infer EO ? IO extends '_none_' ? never : IsNever extends false ? Exclude : Exclude : AllCrudOperations : AllCrudOperations : AllCrudOperations : AllCrudOperations; type GetIncludedOperations, Model extends string> = 'models' extends keyof Slicing ? Slicing extends { models: infer Config; } ? Uncapitalize extends keyof Config ? 'includedOperations' extends keyof Config[Uncapitalize] ? Config[Uncapitalize] extends { includedOperations: readonly []; } ? '_none_' : Config[Uncapitalize] extends { includedOperations: readonly (infer IO)[]; } ? IO : never : GetAllIncludedOperations : GetAllIncludedOperations : AllCrudOperations : AllCrudOperations; type GetAllIncludedOperations> = 'models' extends keyof Slicing ? Slicing extends { models: infer Config; } ? '$all' extends keyof Config ? Config['$all'] extends { includedOperations: readonly []; } ? '_none_' : Config['$all'] extends { includedOperations: readonly (infer IO)[]; } ? IO : AllCrudOperations : AllCrudOperations : AllCrudOperations : AllCrudOperations; type GetExcludedOperations, Model extends string> = 'models' extends keyof Slicing ? Slicing extends { models: infer Config; } ? Uncapitalize extends keyof Config ? Config[Uncapitalize] extends { excludedOperations: readonly (infer EO)[]; } ? EO : GetAllExcludedOperations : GetAllExcludedOperations : never : never; type GetAllExcludedOperations> = 'models' extends keyof Slicing ? Slicing extends { models: infer M; } ? '$all' extends keyof M ? M['$all'] extends { excludedOperations: readonly (infer EO)[]; } ? EO : never : never : never : never; /** * Filters procedures based on slicing configuration. */ type GetSlicedProcedures> = Options['slicing'] extends infer S ? S extends SlicingOptions ? S['includedProcedures'] extends readonly (infer IncludedProc)[] ? Exclude>, S['excludedProcedures'] extends readonly (infer ExcludedProc)[] ? Extract> : never> : Exclude, S['excludedProcedures'] extends readonly (infer ExcludedProc)[] ? Extract> : never> : GetProcedureNames : GetProcedureNames; /** * Filters filter kinds for a specific field, considering field-level slicing configuration with $all fallback. */ type GetSlicedFilterKindsForField, Field extends string, Options extends QueryOptions> = Options extends { slicing: infer S; } ? S extends SlicingOptions ? GetFieldIncludedFilterKinds extends infer IFK ? GetFieldExcludedFilterKinds extends infer EFK ? '_none_' extends IFK ? never : IsNever extends true ? IsNever extends true ? FilterKind : Exclude : Exclude : FilterKind : FilterKind : FilterKind : FilterKind; type GetIncludedFilterKindsFromModelConfig = ModelConfig extends { includedFilterKinds: readonly []; } ? '_none_' : 'fields' extends keyof ModelConfig ? ModelConfig['fields'] extends infer FieldsConfig ? Field extends keyof FieldsConfig ? 'includedFilterKinds' extends keyof FieldsConfig[Field] ? FieldsConfig[Field] extends { includedFilterKinds: readonly []; } ? '_none_' : FieldsConfig[Field] extends { includedFilterKinds: readonly (infer IFK)[]; } ? IFK : never : GetAllFieldsIncludedFilterKinds : GetAllFieldsIncludedFilterKinds : never : never; type GetFieldIncludedFilterKinds, Model extends string, Field extends string> = S extends { models?: infer Config; } ? Uncapitalize extends keyof Config ? GetIncludedFilterKindsFromModelConfig], Field> : '$all' extends keyof Config ? GetIncludedFilterKindsFromModelConfig : never : never; type GetAllFieldsIncludedFilterKinds = '$all' extends keyof FieldsConfig ? FieldsConfig['$all'] extends { includedFilterKinds: readonly []; } ? '_none_' : FieldsConfig['$all'] extends { includedFilterKinds: readonly (infer IFK)[]; } ? IFK : never : never; type GetExcludedFilterKindsFromModelConfig = 'fields' extends keyof ModelConfig ? ModelConfig['fields'] extends infer FieldsConfig ? Field extends keyof FieldsConfig ? FieldsConfig[Field] extends { excludedFilterKinds: readonly (infer EFK)[]; } ? EFK : GetAllFieldsExcludedFilterKinds : GetAllFieldsExcludedFilterKinds : never : never; type GetFieldExcludedFilterKinds, Model extends string, Field extends string> = S extends { models?: infer Config; } ? Uncapitalize extends keyof Config ? GetExcludedFilterKindsFromModelConfig], Field> : '$all' extends keyof Config ? GetExcludedFilterKindsFromModelConfig : never : never; type GetAllFieldsExcludedFilterKinds = '$all' extends keyof FieldsConfig ? FieldsConfig['$all'] extends { excludedFilterKinds: readonly (infer EFK)[]; } ? EFK : never : never; //#endregion //#region src/client/crud-types.d.ts type DefaultModelResult, Omit = undefined, Options extends QueryOptions = QueryOptions, Optional = false, Array = false, IsGenericModel = ([string] extends [Model] ? true : false)> = WrapType : IsDelegateModel extends true ? DelegateUnionResult, Omit> : FlatModelResult, Optional, Array>; type ShouldOmitField, Options extends QueryOptions, Field extends GetModelFields, Omit> = QueryLevelOmit extends boolean ? QueryLevelOmit : OptionsLevelOmit extends boolean ? OptionsLevelOmit : SchemaLevelOmit; type QueryLevelOmit, Field extends GetModelFields, Omit> = Field extends keyof Omit ? (Omit[Field] extends boolean ? Omit[Field] : undefined) : undefined; type OptionsLevelOmit, Field extends GetModelFields, Options extends QueryOptions> = Uncapitalize extends keyof Options['omit'] ? Field extends keyof Options['omit'][Uncapitalize] ? Options['omit'][Uncapitalize][Field] extends boolean ? Options['omit'][Uncapitalize][Field] : undefined : undefined : undefined; type SchemaLevelOmit, Field extends GetModelFields> = GetModelField['omit'] extends true ? true : false; type FlatModelResult, Omit, Options extends QueryOptions> = { [Key in NonRelationFields as ShouldOmitField extends true ? never : Key]: MapModelFieldType }; type DelegateUnionResult, Options extends QueryOptions, SubModel extends GetModels, Omit = undefined, Depth extends readonly 0[] = []> = Depth['length'] extends 10 ? SubModel extends string ? FlatModelResult & { [K in GetModelDiscriminator]: GetModelDelegateMapValue } : never : SubModel extends string ? IsDelegateModel extends true ? // sub-model is itself a delegate — recurse into its own sub-models so all DelegateUnionResult, Omit, [...Depth, 0]> & { [K in GetModelDiscriminator]: GetModelDelegateMapValue } : // leaf model — produce a flat scalar result and fix the discriminator FlatModelResult & { [K in GetModelDiscriminator]: GetModelDelegateMapValue } : never; type ModelSelectResult, Select, Omit, Options extends QueryOptions, ExtResult extends ExtResultBase = {}> = { [Key in keyof Select as Select[Key] extends false | undefined ? never : Key extends keyof ExtractExtResult ? never : Key extends '_count' ? Select[Key] extends SelectCount ? Key : never : Key extends keyof Omit ? Omit[Key] extends true ? never : Key : Key]: Key extends '_count' ? SelectCountResult : Key extends NonRelationFields ? MapModelFieldType : Key extends RelationFields ? ModelResult, Select[Key], Options, ModelFieldIsOptional, FieldIsArray, ExtResult> : never }; type SelectCountResult, C> = C extends true ? { [Key in RelationFields as FieldIsArray extends true ? Key : never]: number } : C extends { select: infer S; } ? { [Key in keyof S]: number } : never; type ModelResult, Args = {}, Options extends QueryOptions = QueryOptions, Optional = false, Array = false, ExtResult extends ExtResultBase = {}> = WrapType<(Args extends { select: infer S extends object; omit?: infer O extends object; } & Record ? ModelSelectResult : Args extends { include: infer I extends object; omit?: infer O extends object; } & Record ? // select all non-omitted scalar fields DefaultModelResult & { [Key in keyof I & RelationFields as I[Key] extends false | undefined ? never : Key]: ModelResult, I[Key], Options, ModelFieldIsOptional, FieldIsArray, ExtResult> } & ('_count' extends keyof I ? I['_count'] extends false | undefined ? {} : { _count: SelectCountResult; } : {}) : Args extends { omit: infer O; } & Record ? DefaultModelResult : DefaultModelResult) & SelectAwareExtResult, Optional, Array>; type SimplifiedResult, Args = {}, Options extends QueryOptions = QueryOptions, Optional = false, Array = false, ExtResult extends ExtResultBase = {}> = Simplify>; type SimplifiedPlainResult, Args = {}, Options extends QueryOptions = QueryOptions, ExtResult extends ExtResultBase = {}> = Simplify>; type TypeDefResult, Partial extends boolean = false> = PartialIf]: MapFieldDefType, Partial> }, Partial extends true ? never : keyof { [Key in GetTypeDefFields as TypeDefFieldIsOptional extends true ? Key : never]: true }>, Partial> & Record; type BatchResult = { count: number; }; type WhereInput, Options extends QueryOptions = QueryOptions, ScalarOnly extends boolean = false, WithAggregations extends boolean = false> = { [Key in GetModelFields as ScalarOnly extends true ? Key extends RelationFields ? never : Key : Key]?: FieldFilter } & { $expr?: (eb: ExpressionBuilder, Model>) => OperandExpression; } & { AND?: OrArray>; OR?: WhereInput[]; NOT?: OrArray>; }; type FieldFilter, Field extends GetModelFields, Options extends QueryOptions, WithAggregations extends boolean, AllowedKinds extends FilterKind = GetSlicedFilterKindsForField> = Field extends RelationFields ? RelationFilter : FieldIsArray extends true ? ArrayFilter, AllowedKinds> : GetModelFieldType extends GetEnums ? EnumFilter, ModelFieldIsOptional, WithAggregations, AllowedKinds> : GetModelFieldType extends GetTypeDefs ? TypedJsonFilter, FieldIsArray, ModelFieldIsOptional, AllowedKinds> : GetModelFieldType extends 'String' ? AddFullTextFilterIfSupported, ModelFieldIsOptional, WithAggregations, AllowedKinds>>> : PrimitiveFilter, ModelFieldIsOptional, WithAggregations, AllowedKinds>; /** * Conditionally augments a string-field filter with the `fuzzy` operator when: * 1. The `Fuzzy` filter kind is allowed for this field, AND * 2. The schema's provider supports fuzzy search (postgres only), AND * 3. The field is annotated with `@fuzzy` in the ZModel schema. * * Caller is responsible for only invoking this on String-typed fields * (the gate lives in `FieldFilter`). */ type AddFuzzyFilterIfSupported, Field extends GetModelFields, AllowedKinds extends FilterKind, Base> = 'Fuzzy' extends AllowedKinds ? ProviderSupportsFuzzy extends true ? GetModelField['fuzzy'] extends true ? Base & { /** * Performs a fuzzy search on the string field. Only available when * the schema's provider is `postgresql` (requires `pg_trgm` extension) * and the field is annotated with `@fuzzy` in the ZModel schema. * See {@link FuzzyFilterPayload} for the full options reference. */ fuzzy?: FuzzyFilterPayload; } : Base : Base : Base; /** * Conditionally augments a string-field filter with the `fts` operator when: * 1. The `FullText` filter kind is allowed for this field, AND * 2. The schema's provider supports full-text search (postgres only), AND * 3. The field is annotated with `@fullText` in the ZModel schema. * * Caller is responsible for only invoking this on String-typed fields * (the gate lives in `FieldFilter`). */ type AddFullTextFilterIfSupported, Field extends GetModelFields, AllowedKinds extends FilterKind, Base> = 'FullText' extends AllowedKinds ? ProviderSupportsFullText extends true ? GetModelField['fullText'] extends true ? Base & { /** * Performs a full-text search on the string field. Only available when * the schema's provider is `postgresql` and the field is annotated with * `@fullText` in the ZModel schema. * See {@link FullTextFilterPayload} for the full options reference. */ fts?: FullTextFilterPayload; } : Base : Base : Base; type EnumFilter, Nullable extends boolean, WithAggregations extends boolean, AllowedKinds extends FilterKind> = ('Equality' extends AllowedKinds ? NullableIf, Nullable> : never) | (('Equality' extends AllowedKinds ? { /** * Checks for equality with the specified enum value. */ equals?: NullableIf, Nullable>; /** * Checks if the enum value is in the specified list of values. */ in?: (keyof GetEnum)[]; /** * Checks if the enum value is not in the specified list of values. */ notIn?: (keyof GetEnum)[]; } : {}) & { /** * Builds a negated filter. */ not?: EnumFilter; } & (WithAggregations extends true ? { /** * Filters against the count of records. */ _count?: NumberFilter<'Int', false, false, AllowedKinds>; /** * Filters against the minimum value. */ _min?: EnumFilter; /** * Filters against the maximum value. */ _max?: EnumFilter; } : {})); type ArrayFilter = ('Equality' extends AllowedKinds ? { /** * Checks if the array equals the specified array. */ equals?: MapScalarType[] | null; } : {}) & ('List' extends AllowedKinds ? { /** * Checks if the array contains all elements of the specified array. */ has?: MapScalarType | null; /** * Checks if the array contains any of the elements of the specified array. */ hasEvery?: MapScalarType[]; /** * Checks if the array contains some of the elements of the specified array. */ hasSome?: MapScalarType[]; /** * Checks if the array is empty. */ isEmpty?: boolean; } : {}); type MapScalarType = Type extends GetEnums ? keyof GetEnum : MapBaseType$1; type PrimitiveFilter = T extends 'String' ? StringFilter : T extends 'Int' | 'Float' | 'Decimal' | 'BigInt' ? NumberFilter : T extends 'Boolean' ? BooleanFilter : T extends 'DateTime' ? DateTimeFilter : T extends 'Bytes' ? BytesFilter : T extends 'Json' ? JsonFilter : never; type CommonPrimitiveFilter = ('Equality' extends AllowedKinds ? { /** * Checks for equality with the specified value. */ equals?: NullableIf; /** * Checks if the value is in the specified list of values. */ in?: DataType[]; /** * Checks if the value is not in the specified list of values. */ notIn?: DataType[]; } : {}) & ('Range' extends AllowedKinds ? { /** * Checks if the value is less than the specified value. */ lt?: DataType; /** * Checks if the value is less than or equal to the specified value. */ lte?: DataType; /** * Checks if the value is greater than the specified value. */ gt?: DataType; /** * Checks if the value is greater than or equal to the specified value. */ gte?: DataType; /** * Checks if the value is between the specified values (inclusive). */ between?: [start: DataType, end: DataType]; } : {}) & { /** * Builds a negated filter. */ not?: PrimitiveFilter; }; type StringFilter = ('Equality' extends AllowedKinds ? NullableIf : never) | (CommonPrimitiveFilter & ('Like' extends AllowedKinds ? { /** * Checks if the string contains the specified substring. */ contains?: string; /** * Checks if the string starts with the specified substring. */ startsWith?: string; /** * Checks if the string ends with the specified substring. */ endsWith?: string; /** * Specifies the string comparison mode. Not effective for "sqlite" provider */ mode?: 'default' | 'insensitive'; } : {}) & (WithAggregations extends true ? { /** * Filters against the count of records. */ _count?: NumberFilter<'Int', false, false, AllowedKinds>; /** * Filters against the minimum value. */ _min?: StringFilter; /** * Filters against the maximum value. */ _max?: StringFilter; } : {})); type NumberFilter = ('Equality' extends AllowedKinds ? NullableIf : never) | (CommonPrimitiveFilter & (WithAggregations extends true ? { /** * Filters against the count of records. */ _count?: NumberFilter<'Int', false, false, AllowedKinds>; /** * Filters against the average value. */ _avg?: NumberFilter; /** * Filters against the sum value. */ _sum?: NumberFilter; /** * Filters against the minimum value. */ _min?: NumberFilter; /** * Filters against the maximum value. */ _max?: NumberFilter; } : {})); type DateTimeFilter = ('Equality' extends AllowedKinds ? NullableIf : never) | (CommonPrimitiveFilter & (WithAggregations extends true ? { /** * Filters against the count of records. */ _count?: NumberFilter<'Int', false, false, AllowedKinds>; /** * Filters against the minimum value. */ _min?: DateTimeFilter; /** * Filters against the maximum value. */ _max?: DateTimeFilter; } : {})); type BytesFilter = ('Equality' extends AllowedKinds ? NullableIf : never) | (('Equality' extends AllowedKinds ? { /** * Checks for equality with the specified value. */ equals?: NullableIf; /** * Checks if the value is in the specified list of values. */ in?: Uint8Array[]; /** * Checks if the value is not in the specified list of values. */ notIn?: Uint8Array[]; } : {}) & { /** * Builds a negated filter. */ not?: BytesFilter; } & (WithAggregations extends true ? { /** * Filters against the count of records. */ _count?: NumberFilter<'Int', false, false, AllowedKinds>; /** * Filters against the minimum value. */ _min?: BytesFilter; /** * Filters against the maximum value. */ _max?: BytesFilter; } : {})); type BooleanFilter = ('Equality' extends AllowedKinds ? NullableIf : never) | (('Equality' extends AllowedKinds ? { /** * Checks for equality with the specified value. */ equals?: NullableIf; } : {}) & { /** * Builds a negated filter. */ not?: BooleanFilter; } & (WithAggregations extends true ? { /** * Filters against the count of records. */ _count?: NumberFilter<'Int', false, false, AllowedKinds>; /** * Filters against the minimum value. */ _min?: BooleanFilter; /** * Filters against the maximum value. */ _max?: BooleanFilter; } : {})); type JsonFilter = ('Equality' extends AllowedKinds ? { /** * Checks for equality with the specified value. */ equals?: JsonValue | JsonNullValues; /** * Builds a negated filter. */ not?: JsonValue | JsonNullValues; } : {}) & ('Json' extends AllowedKinds ? { /** * JSON path to select the value to filter on. If omitted, the whole JSON value is used. */ path?: string; /** * Checks if the value is a string and contains the specified substring. */ string_contains?: string; /** * Checks if the value is a string and starts with the specified substring. */ string_starts_with?: string; /** * Checks if the value is a string and ends with the specified substring. */ string_ends_with?: string; /** * String comparison mode. Not effective for "sqlite" provider */ mode?: 'default' | 'insensitive'; /** * Checks if the value is an array and contains the specified value. */ array_contains?: JsonValue; /** * Checks if the value is an array and starts with the specified value. */ array_starts_with?: JsonValue; /** * Checks if the value is an array and ends with the specified value. */ array_ends_with?: JsonValue; } : {}); type TypedJsonFilter, Array extends boolean, Optional extends boolean, AllowedKinds extends FilterKind> = (JsonFilter & { [Key in GetTypeDefFields]?: never }) | (TypedJsonTypedFilter & { [Key in keyof JsonFilter]?: never }) | (Optional extends true ? null | JsonNullValues : never); type TypedJsonTypedFilter, Array extends boolean, AllowedKinds extends FilterKind> = 'Json' extends AllowedKinds ? Array extends true ? ArrayTypedJsonFilter : NonArrayTypedJsonFilter : {}; type ArrayTypedJsonFilter, AllowedKinds extends FilterKind> = { some?: TypedJsonFieldsFilter; every?: TypedJsonFieldsFilter; none?: TypedJsonFieldsFilter; }; type NonArrayTypedJsonFilter, AllowedKinds extends FilterKind> = { is?: TypedJsonFieldsFilter; isNot?: TypedJsonFieldsFilter; } | TypedJsonFieldsFilter; type TypedJsonFieldsFilter, AllowedKinds extends FilterKind> = { [Key in GetTypeDefFields]?: GetTypeDefFieldType extends GetTypeDefs ? TypedJsonFilter, TypeDefFieldIsArray, TypeDefFieldIsOptional, AllowedKinds> : TypeDefFieldIsArray extends true ? ArrayFilter, AllowedKinds> : GetTypeDefFieldType extends GetEnums ? EnumFilter, TypeDefFieldIsOptional, false, AllowedKinds> : PrimitiveFilter, TypeDefFieldIsOptional, false, AllowedKinds> }; type SortOrder = 'asc' | 'desc'; type NullsOrder = 'first' | 'last'; type StringFields> = { [Key in NonRelationFields]: MapModelFieldType extends string | null ? Key : never }[NonRelationFields]; /** * String fields that have been annotated with `@fuzzy` and are therefore eligible * for `_fuzzyRelevance` ordering. */ type FuzzyFields> = { [Key in StringFields]: GetModelField['fuzzy'] extends true ? Key : never }[StringFields]; /** * Payload for the `fuzzy` string filter operator. Performs a fuzzy search using * PostgreSQL `pg_trgm` (only available when the schema's provider is `postgresql`). * Not supported on MySQL or SQLite (throws `NotSupported` at runtime). * * Modes: * - `'simple'` (default): trigram similarity on the whole value (operator `%`, * function `similarity()`). * - `'word'`: word similarity — checks if the search term is approximately * contained as a word inside the value (operator `<%`, * function `word_similarity()`). * - `'strictWord'`: stricter variant of `'word'` (operator `<<%`, * function `strict_word_similarity()`). * * When `threshold` is provided the function form is used * (`similarity() > threshold`) instead of the operator form, so the * `pg_trgm.*_threshold` session settings are bypassed. * * `unaccent` is opt-in (defaults to `false`) — set it to `true` to make the * comparison accent-insensitive. Enabling it requires the `unaccent` extension * to be installed on the database. */ type FuzzyFilterPayload = { /** * Search term to match against (must be a non-empty string). */ search: string; /** * Matching mode. Defaults to `'simple'`. */ mode?: 'simple' | 'word' | 'strictWord'; /** * Optional similarity threshold in `[0, 1]`. When provided, the function * form is used and matches require `similarity > threshold`. */ threshold?: number; /** * Whether to apply `unaccent()` to both sides. Defaults to `false`. * Set to `true` to enable accent-insensitive matching (requires the * `unaccent` extension on PostgreSQL). */ unaccent?: boolean; }; type FuzzyRelevanceOrderBy> = { /** * Sorts by fuzzy search relevance using PostgreSQL `pg_trgm` similarity functions. * Not supported on MySQL or SQLite (throws `NotSupported` at runtime). * Cannot be combined with cursor-based pagination. */ _fuzzyRelevance?: { /** * String fields annotated with `@fuzzy` to compute relevance against (must be non-empty). * * When multiple fields are provided, the row's relevance score is the * greatest per-field similarity, i.e. `GREATEST(similarity(field1, search), similarity(field2, search), ...)`. */ fields: [FuzzyFields, ...FuzzyFields[]]; /** * The search term to compute relevance for. */ search: string; /** * Fuzzy matching mode used to compute relevance. */ mode?: 'simple' | 'word' | 'strictWord'; /** * Whether to remove accents before computing relevance. */ unaccent?: boolean; /** * Sort direction. */ sort: SortOrder; }; }; /** * String fields that have been annotated with `@fullText` and are therefore eligible * for `_ftsRelevance` ordering. */ type FullTextFields> = { [Key in StringFields]: GetModelField['fullText'] extends true ? Key : never }[StringFields]; /** * Payload for the `fts` string filter operator. Performs full-text search using * PostgreSQL `to_tsvector` / `to_tsquery` (postgresql provider only). * * Query syntax follows `to_tsquery`: callers write raw `&` (AND), `|` (OR), * `!` (NOT), `<->` (FOLLOWED BY). Malformed queries throw at SQL execution time. */ type FullTextFilterPayload = { /** * Search query in `to_tsquery` syntax (must be a non-empty string). */ search: string; /** * Postgres text-search configuration (e.g. `'english'`, `'simple'`). When * omitted, the database's `default_text_search_config` setting is used — * the SQL is emitted as `to_tsvector(field) @@ to_tsquery(query)` without * an explicit regconfig argument. */ config?: string; }; type FtsRelevanceOrderBy> = { /** * Sorts by full-text-search relevance using PostgreSQL `ts_rank`. */ _ftsRelevance?: { /** * String fields annotated with `@fullText` to compute relevance against (must be non-empty). * * When multiple fields are provided, the fields are concatenated with a * space separator and a single `ts_rank` is computed over the combined * document — i.e. `ts_rank(to_tsvector(concat_ws(' ', f1, f2, ...)), q)`. * This means an AND query (e.g. `'cat & dog'`) matches rows where the * terms appear across different fields, not just within the same field. */ fields: [FullTextFields, ...FullTextFields[]]; /** * The search term to compute relevance for (in `to_tsquery` syntax). */ search: string; /** * Postgres text-search configuration. When omitted, the database's * `default_text_search_config` setting is used. */ config?: string; /** * Sort direction. */ sort: SortOrder; }; }; type OrderBy, WithRelation extends boolean, WithAggregation extends boolean> = { [Key in NonRelationFields]?: ModelFieldIsOptional extends true ? SortOrder | { /** * Sort order */ sort: SortOrder; /** * Treatment of null values */ nulls?: NullsOrder; } : SortOrder } & (WithRelation extends true ? { [Key in RelationFields]?: FieldIsArray extends true ? { /** * Sorts by the count of related records. */ _count?: SortOrder; } : OrderBy, WithRelation, WithAggregation> } : {}) & (WithAggregation extends true ? { /** * Sorts by the count of records. */ _count?: OrderBy; /** * Sorts by the minimum value. */ _min?: MinMaxInput; /** * Sorts by the maximum value. */ _max?: MinMaxInput; } & (NumericFields extends never ? {} : { /** * Sorts by the average value. */ _avg?: SumAvgInput; /** * Sorts by the sum value. */ _sum?: SumAvgInput; }) : {}); type WhereUniqueInput, Options extends QueryOptions> = AtLeast<{ [Key in keyof GetModel['uniqueFields']]?: GetModel['uniqueFields'][Key] extends Pick ? MapFieldDefType['uniqueFields'][Key]> : { [Key1 in keyof GetModel['uniqueFields'][Key]]: GetModel['uniqueFields'][Key][Key1] extends Pick ? MapFieldDefType['uniqueFields'][Key][Key1]> : never } } & WhereInput, Extract['uniqueFields'], string>>; type OmitInput> = { [Key in NonRelationFields]?: boolean }; type SelectIncludeOmit, AllowCount extends boolean, Options extends QueryOptions = QueryOptions, AllowRelation extends boolean = true, ExtResult extends ExtResultBase = {}> = { /** * Explicitly select fields and relations to be returned by the query. */ select?: (SelectInput & ExtResultSelectOmitFields) | null; /** * Explicitly omit fields from the query result. */ omit?: (OmitInput & ExtResultSelectOmitFields) | null; } & { [K in AllowRelation extends true ? RelationFields extends never ? never : 'include' : never]?: IncludeInput | null }; type SelectInput, Options extends QueryOptions = QueryOptions, AllowCount extends boolean = true, AllowRelation extends boolean = true, ExtResult extends ExtResultBase = {}> = { [Key in NonRelationFields]?: boolean } & (AllowRelation extends true ? IncludeInput : {}); type SelectCount, Options extends QueryOptions> = boolean | { /** * Selects specific relations to count. */ select: { [Key in RelationFields as FieldIsArray extends true ? Key : never]?: boolean | { where: WhereInput, Options, false>; } }; }; type IncludeInput, Options extends QueryOptions = QueryOptions, AllowCount extends boolean = true, ExtResult extends ExtResultBase = {}> = { [Key in RelationFields as RelationFieldType extends GetSlicedModels ? Key : never]?: boolean | FindArgs, Options, FieldIsArray, FieldIsArray extends true ? true : ModelFieldIsOptional extends true ? true : false, ExtResult> } & (AllowCount extends true ? HasToManyRelations extends true ? { _count?: SelectCount; } : {} : {}); type Subset = { [key in keyof T]: key extends keyof U ? T[key] : never }; type SelectSubset = { [key in keyof T]: key extends keyof U ? T[key] : never } & (T extends { select: any; include: any; } ? 'Please either choose `select` or `include`.' : T extends { select: any; omit: any; } ? 'Please either choose `select` or `omit`.' : {}); type ToManyRelationFilter, in out Field extends RelationFields, Options extends QueryOptions> = { every?: WhereInput, Options>; some?: WhereInput, Options>; none?: WhereInput, Options>; }; type ToOneRelationFilter, Field extends RelationFields, Options extends QueryOptions> = NullableIf, Options> & { /** * Checks if the related record matches the specified filter. */ is?: NullableIf, Options>, ModelFieldIsOptional>; /** * Checks if the related record does not match the specified filter. */ isNot?: NullableIf, Options>, ModelFieldIsOptional>; }, ModelFieldIsOptional>; type RelationFilter, Field extends RelationFields, Options extends QueryOptions, AllowedKinds extends FilterKind> = 'Relation' extends AllowedKinds ? FieldIsArray extends true ? ToManyRelationFilter : ToOneRelationFilter : never; type MapModelFieldType, Field extends GetModelFields> = MapFieldDefType>; type MapFieldDefType, Partial extends boolean = false> = WrapType ? keyof GetEnum : T['type'] extends GetTypeDefs ? TypeDefResult & Record : MapBaseType$1, T['optional'], T['array']>; type OptionalFieldsForCreate> = keyof { [Key in GetModelFields as ModelFieldIsOptional extends true ? Key : FieldHasDefault extends true ? Key : FieldIsArray extends true ? Key : GetModelField['updatedAt'] extends true | UpdatedAtInfo ? Key : never]: GetModelField }; type GetRelation, Field extends GetModelFields> = GetModelField['relation']; type OppositeRelation, Field extends GetModelFields, FT = FieldType> = FT extends GetModels ? GetRelation extends RelationInfo ? GetRelation['opposite'] extends GetModelFields ? Schema['models'][FT]['fields'][GetRelation['opposite']]['relation'] : never : never : never; type OppositeRelationFields, Field extends GetModelFields, Opposite = OppositeRelation> = Opposite extends RelationInfo ? (Opposite['fields'] extends readonly string[] ? Opposite['fields'] : []) : []; type OppositeRelationAndFK, Field extends GetModelFields, FT = FieldType, Relation = GetModelField['relation'], Opposite = (Relation extends RelationInfo ? Relation['opposite'] : never)> = FT extends GetModels ? Opposite extends GetModelFields ? Opposite | OppositeRelationFields[number] : never : never; type FilterArgs, in out Options extends QueryOptions> = { /** * Filter conditions */ where?: WhereInput; }; type SortAndTakeArgs, in out Options extends QueryOptions> = { /** * Number of records to skip */ skip?: number; /** * Number of records to take */ take?: number; /** * Order by clauses */ orderBy?: OrArray & (ProviderSupportsFuzzy extends true ? FuzzyRelevanceOrderBy : {}) & (ProviderSupportsFullText extends true ? FtsRelevanceOrderBy : {})>; /** * Cursor for pagination */ cursor?: WhereUniqueInput; }; type FindArgs, Options extends QueryOptions, Collection extends boolean, AllowFilter extends boolean = true, ExtResult extends ExtResultBase = {}> = (Collection extends true ? SortAndTakeArgs & (ProviderSupportsDistinct extends true ? { /** * Distinct fields. Only supported by providers that natively support SQL "DISTINCT ON". */ distinct?: OrArray>; } : {}) : {}) & (AllowFilter extends true ? FilterArgs : {}) & SelectIncludeOmit; type FindManyArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = FindArgs & ExtractExtQueryArgs; type FindFirstArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = FindArgs & ExtractExtQueryArgs; type ExistsArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}> = FilterArgs & ExtractExtQueryArgs; type FindUniqueArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = { where: WhereUniqueInput; } & SelectIncludeOmit & ExtractExtQueryArgs; type CreateArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = { data: CreateInput; } & SelectIncludeOmit & ExtractExtQueryArgs; type CreateManyArgs, _Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}> = CreateManyInput & ExtractExtQueryArgs; type CreateManyAndReturnArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = CreateManyInput & SelectIncludeOmit & ExtractExtQueryArgs; type OptionalWrap, T extends object> = Optional>; type CreateScalarPayload> = OptionalWrap as FieldIsDelegateDiscriminator extends true ? never : Key]: ScalarCreatePayload }>; type ScalarCreatePayload, Field extends ScalarFields> = ScalarFieldMutationPayload | (FieldIsArray extends true ? { set?: MapModelFieldType; } : never); type ScalarFieldMutationPayload, Field extends GetModelFields> = IsJsonField extends true ? ModelFieldIsOptional extends true ? JsonValue | JsonNull | DbNull : JsonValue | JsonNull : IsTypedJsonField extends true ? ModelFieldIsOptional extends true ? MapModelFieldType | JsonNull | DbNull : MapModelFieldType : MapModelFieldType; type IsJsonField, Field extends GetModelFields> = GetModelFieldType extends 'Json' ? true : false; type IsTypedJsonField, Field extends GetModelFields> = GetModelFieldType extends GetTypeDefs ? true : false; type CreateFKPayload> = OptionalWrap]: MapModelFieldType }>; type RelationModelAllowsCreate, Field extends RelationFields> = GetModelFieldType extends GetModels ? ModelAllowsCreate> : false; type CreateRelationFieldPayload, Field extends RelationFields, Options extends QueryOptions> = Omit<{ /** * Connects or create a related record. */ connectOrCreate?: ConnectOrCreateInput; /** * Creates a related record. */ create?: NestedCreateInput; /** * Creates a batch of related records. */ createMany?: NestedCreateManyInput; /** * Connects an existing record. */ connect?: ConnectInput; }, (FieldIsArray extends true ? never : 'createMany') | (RelationModelAllowsCreate extends true ? never : 'create' | 'createMany' | 'connectOrCreate')>; type CreateRelationPayload, Options extends QueryOptions> = OptionalWrap as RelationFieldType extends GetSlicedModels ? Key : never]: CreateRelationFieldPayload }>; /** * Create input type that uses FK scalar fields (e.g., `authorId`) instead of * relation objects. */ type UncheckedCreateInput, Options extends QueryOptions = QueryOptions> = CreateScalarPayload & CreateFKPayload & CreateWithNonOwnedRelationPayload; /** * Create input type that uses relation objects (e.g., `author: { connect: … }`) * instead of FK scalar fields. */ type CheckedCreateInput, Options extends QueryOptions = QueryOptions> = CreateScalarPayload & CreateRelationPayload; type CreateWithNonOwnedRelationPayload, Options extends QueryOptions> = OptionalWrap as RelationFieldType extends GetSlicedModels ? Key : never]: CreateRelationFieldPayload }>; type ConnectOrCreatePayload, Options extends QueryOptions, Without extends string = never> = { /** * The unique filter to find an existing record to connect. */ where: WhereUniqueInput; /** * The data to create a new record if no existing record is found. */ create: CreateInput; }; type CreateManyInput, Without extends string = never> = { /** * The data for the records to create. */ data: OrArray, Without> & Omit, Without>>; /** * Specifies whether to skip creating records that would violate unique constraints. */ skipDuplicates?: boolean; }; type CreateInput, Options extends QueryOptions, Without extends string = never> = XOR, Without>, Omit, Without>>; type NestedCreateInput, Field extends RelationFields, Options extends QueryOptions> = OrArray, Options, OppositeRelationAndFK>, FieldIsArray>; type NestedCreateManyInput, Field extends RelationFields> = CreateManyInput, OppositeRelationAndFK>; type UpdateArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = { /** * The data to update the record with. */ data: UpdateInput; /** * The unique filter to find the record to update. */ where: WhereUniqueInput; } & SelectIncludeOmit & ExtractExtQueryArgs; type UpdateManyArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}> = UpdateManyPayload & ExtractExtQueryArgs; type UpdateManyAndReturnArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = UpdateManyPayload & SelectIncludeOmit & ExtractExtQueryArgs; type UpdateManyPayload, out Options extends QueryOptions = QueryOptions, Without extends string = never> = { /** * The data to update the records with. */ data: OrArray & UpdateFKPayload>; /** * The filter to select records to update. */ where?: WhereInput; /** * Limit the number of records to update. */ limit?: number; }; type UpsertArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = { /** * The data to create the record if it doesn't exist. */ create: CreateInput; /** * The data to update the record with if it exists. */ update: UpdateInput; /** * The unique filter to find the record to update. */ where: WhereUniqueInput; } & SelectIncludeOmit & ExtractExtQueryArgs; type UpdateScalarInput, Without extends string = never> = Omit<{ [Key in Exclude, ForeignKeyFields> as FieldIsDelegateDiscriminator extends true ? never : Key]?: ScalarUpdatePayload }, Without>; type UpdateFKPayload, Without extends string = never> = Omit<{ [Key in ForeignKeyFields]?: MapModelFieldType }, Without>; type ScalarUpdatePayload, Field extends NonRelationFields> = ScalarFieldMutationPayload | (Field extends NumericFields ? { /** * Sets the field to the specified value. */ set?: NullableIf>; /** * Increments the field by the specified value. */ increment?: number; /** * Decrements the field by the specified value. */ decrement?: number; /** * Multiplies the field by the specified value. */ multiply?: number; /** * Divides the field by the specified value. */ divide?: number; } : never) | (FieldIsArray extends true ? { /** * Sets the field to the specified array. */ set?: MapModelFieldType[]; /** * Appends the specified values to the array field. */ push?: OrArray, true>; } : never); type UpdateRelationInput, Options extends QueryOptions, Without extends string = never> = Omit<{ [Key in RelationFields as RelationFieldType extends GetSlicedModels ? Key : never]?: UpdateRelationFieldPayload }, Without>; type UpdateNonOwnedRelationInput, Options extends QueryOptions = QueryOptions> = { [Key in NonOwnedRelationFields as RelationFieldType extends GetSlicedModels ? Key : never]?: UpdateRelationFieldPayload }; /** * Update input type that uses FK scalar fields (e.g., `authorId`) instead of * relation objects. */ type UncheckedUpdateInput, Options extends QueryOptions = QueryOptions> = UpdateScalarInput & UpdateFKPayload & UpdateNonOwnedRelationInput; /** * Update input type that uses relation objects (e.g., `author: { connect: … }`) * instead of FK scalar fields. */ type CheckedUpdateInput, Options extends QueryOptions = QueryOptions> = UpdateScalarInput & UpdateRelationInput; type UpdateInput, Options extends QueryOptions, Without extends string = never> = XOR, Without>, Omit, Without>>; type UpdateRelationFieldPayload, Field extends RelationFields, Options extends QueryOptions> = FieldIsArray extends true ? ToManyRelationUpdateInput : ToOneRelationUpdateInput; type ToManyRelationUpdateInput, Field extends RelationFields, Options extends QueryOptions> = Omit<{ /** * Creates related records. */ create?: NestedCreateInput; /** * Creates a batch of related records. */ createMany?: NestedCreateManyInput; /** * Connects existing records. */ connect?: ConnectInput; /** * Connects or create related records. */ connectOrCreate?: ConnectOrCreateInput; /** * Disconnects related records. */ disconnect?: DisconnectInput; /** * Updates related records. */ update?: NestedUpdateInput; /** * Upserts related records. */ upsert?: NestedUpsertInput; /** * Updates a batch of related records. */ updateMany?: NestedUpdateManyInput; /** * Deletes related records. */ delete?: NestedDeleteInput; /** * Deletes a batch of related records. */ deleteMany?: NestedDeleteManyInput; /** * Sets the related records to the specified ones. */ set?: SetRelationInput; }, RelationModelAllowsCreate extends true ? never : 'create' | 'createMany' | 'connectOrCreate' | 'upsert'>; type ToOneRelationUpdateInput, in out Field extends RelationFields, in out Options extends QueryOptions> = Omit<{ /** * Creates a related record. */ create?: NestedCreateInput; /** * Connects an existing record. */ connect?: ConnectInput; /** * Connects or create a related record. */ connectOrCreate?: ConnectOrCreateInput; /** * Updates the related record. */ update?: NestedUpdateInput; /** * Upserts the related record. */ upsert?: NestedUpsertInput; } & (ModelFieldIsOptional extends true ? { /** * Disconnects the related record. */ disconnect?: DisconnectInput; /** * Deletes the related record. */ delete?: NestedDeleteInput; } : {}), RelationModelAllowsCreate extends true ? never : 'create' | 'connectOrCreate' | 'upsert'>; type DeleteArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = { /** * The unique filter to find the record to delete. */ where: WhereUniqueInput; } & SelectIncludeOmit & ExtractExtQueryArgs; type DeleteManyArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}> = { /** * Filter to select records to delete. */ where?: WhereInput; /** * Limits the number of records to delete. */ limit?: number; } & ExtractExtQueryArgs; type CountArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}> = Omit, 'select' | 'include' | 'distinct' | 'omit'> & { /** * Selects fields to count */ select?: CountAggregateInput | true; } & ExtractExtQueryArgs; type CountAggregateInput> = { [Key in NonRelationFields]?: true } & { _all?: true; }; type CountResult, Args> = Args extends { select: infer S; } ? S extends true ? number : { [Key in keyof S]: number } : number; type AggregateArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}> = { /** * Filter conditions */ where?: WhereInput; /** * Number of records to skip for the aggregation */ skip?: number; /** * Number of records to take for the aggregation */ take?: number; /** * Order by clauses */ orderBy?: OrArray>; } & { /** * Performs count aggregation. */ _count?: true | CountAggregateInput; /** * Performs minimum value aggregation. */ _min?: MinMaxInput; /** * Performs maximum value aggregation. */ _max?: MinMaxInput; } & (NumericFields extends never ? {} : { /** * Performs average value aggregation. */ _avg?: SumAvgInput; /** * Performs sum value aggregation. */ _sum?: SumAvgInput; }) & ExtractExtQueryArgs; type NumericFields> = keyof { [Key in GetModelFields as GetModelFieldType extends 'Int' | 'Float' | 'BigInt' | 'Decimal' ? FieldIsArray extends true ? never : Key : never]: GetModelField }; type SumAvgInput, ValueType> = { [Key in NumericFields]?: ValueType }; type MinMaxInput, ValueType> = { [Key in GetModelFields as FieldIsArray extends true ? never : FieldIsRelation extends true ? never : Key]?: ValueType }; type AggregateResult, Args> = (Args extends { _count: infer Count; } ? { /** * Count aggregation result */ _count: AggCommonOutput; } : {}) & (Args extends { _sum: infer Sum; } ? { /** * Sum aggregation result */ _sum: AggCommonOutput; } : {}) & (Args extends { _avg: infer Avg; } ? { /** * Average aggregation result */ _avg: AggCommonOutput; } : {}) & (Args extends { _min: infer Min; } ? { /** * Minimum aggregation result */ _min: AggCommonOutput; } : {}) & (Args extends { _max: infer Max; } ? { /** * Maximum aggregation result */ _max: AggCommonOutput; } : {}); type AggCommonOutput = Input extends true ? number : Input extends {} ? { [Key in keyof Input]: number } : never; type GroupByHaving, out Options extends QueryOptions = QueryOptions> = Omit, '$expr'>; type GroupByArgs, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}> = { /** * Filter conditions */ where?: WhereInput; /** * Order by clauses */ orderBy?: OrArray>; /** * Fields to group by */ by: NonRelationFields | NonEmptyArray>; /** * Filter conditions for the grouped records */ having?: GroupByHaving; /** * Number of records to take for grouping */ take?: number; /** * Number of records to skip for grouping */ skip?: number; /** * Performs count aggregation. */ _count?: true | CountAggregateInput; /** * Performs minimum value aggregation. */ _min?: MinMaxInput; /** * Performs maximum value aggregation. */ _max?: MinMaxInput; } & (NumericFields extends never ? {} : { /** * Performs average value aggregation. */ _avg?: SumAvgInput; /** * Performs sum value aggregation. */ _sum?: SumAvgInput; }) & ExtractExtQueryArgs; type GroupByResult, Args extends { by: unknown; }> = Array<{ [Key in NonRelationFields as Key extends ValueOfPotentialTuple ? Key : never]: MapModelFieldType } & (Args extends { _count: infer Count; } ? { /** * Count aggregation result */ _count: AggCommonOutput; } : {}) & (Args extends { _avg: infer Avg; } ? { /** * Average aggregation result */ _avg: AggCommonOutput; } : {}) & (Args extends { _sum: infer Sum; } ? { /** * Sum aggregation result */ _sum: AggCommonOutput; } : {}) & (Args extends { _min: infer Min; } ? { /** * Minimum aggregation result */ _min: AggCommonOutput; } : {}) & (Args extends { _max: infer Max; } ? { /** * Maximum aggregation result */ _max: AggCommonOutput; } : {})>; /** * Maps each CRUD operation name to its argument type for a given model. */ type CrudArgsMap, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = { findMany: FindManyArgs; findUnique: FindUniqueArgs; findUniqueOrThrow: FindUniqueArgs; findFirst: FindFirstArgs; findFirstOrThrow: FindFirstArgs; create: CreateArgs; createMany: CreateManyArgs; createManyAndReturn: CreateManyAndReturnArgs; update: UpdateArgs; updateMany: UpdateManyArgs; updateManyAndReturn: UpdateManyAndReturnArgs; upsert: UpsertArgs; delete: DeleteArgs; deleteMany: DeleteManyArgs; count: CountArgs; aggregate: AggregateArgs; groupBy: GroupByArgs; exists: ExistsArgs; }; /** * Maps a CRUD operation name to its argument type for a given model. */ type CrudArgsType, Op extends AllCrudOperations, Options extends QueryOptions = QueryOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtResult extends ExtResultBase = {}> = CrudArgsMap[Op]; /** * Maps each CRUD operation name to its return type for a given model + args. */ type CrudReturnMap, Args, Options extends QueryOptions = QueryOptions, ExtResult extends ExtResultBase = {}> = { findMany: SimplifiedPlainResult[]; findUnique: SimplifiedPlainResult | null; findUniqueOrThrow: SimplifiedPlainResult; findFirst: SimplifiedPlainResult | null; findFirstOrThrow: SimplifiedPlainResult; create: SimplifiedPlainResult; createMany: BatchResult; createManyAndReturn: SimplifiedPlainResult[]; update: SimplifiedPlainResult; updateMany: BatchResult; updateManyAndReturn: SimplifiedPlainResult[]; upsert: SimplifiedPlainResult; delete: SimplifiedPlainResult; deleteMany: BatchResult; count: CountResult; aggregate: AggregateResult; groupBy: Args extends { by: unknown; } ? GroupByResult : never; exists: boolean; }; /** * Maps a CRUD operation name to its return type for a given model + args. */ type CrudReturnType, Op extends AllCrudOperations, Args, Options extends QueryOptions = QueryOptions, ExtResult extends ExtResultBase = {}> = CrudReturnMap[Op]; type ConnectInput, Field extends RelationFields, Options extends QueryOptions> = FieldIsArray extends true ? OrArray, Options>> : WhereUniqueInput, Options>; type ConnectOrCreateInput, Field extends RelationFields, Options extends QueryOptions> = FieldIsArray extends true ? OrArray, Options, OppositeRelationAndFK>> : ConnectOrCreatePayload, Options, OppositeRelationAndFK>; type DisconnectInput, Field extends RelationFields, Options extends QueryOptions> = FieldIsArray extends true ? OrArray, Options>, true> : boolean | WhereInput, Options>; type SetRelationInput, Field extends RelationFields, Options extends QueryOptions> = OrArray, Options>>; type NestedUpdateInput, Field extends RelationFields, Options extends QueryOptions> = FieldIsArray extends true ? OrArray<{ /** * Unique filter to select the record to update. */ where: WhereUniqueInput, Options>; /** * The data to update the record with. */ data: UpdateInput, Options, OppositeRelationAndFK>; }, true> : XOR<{ /** * Filter to select the record to update. */ where?: WhereInput, Options>; /** * The data to update the record with. */ data: UpdateInput, Options, OppositeRelationAndFK>; }, UpdateInput, Options, OppositeRelationAndFK>>; type NestedUpsertInput, Field extends RelationFields, Options extends QueryOptions> = OrArray<{ /** * Unique filter to select the record to update. */ where: WhereUniqueInput, Options>; /** * The data to create the record if it doesn't exist. */ create: CreateInput, Options, OppositeRelationAndFK>; /** * The data to update the record with if it exists. */ update: UpdateInput, Options, OppositeRelationAndFK>; }, FieldIsArray>; type NestedUpdateManyInput, Field extends RelationFields, Options extends QueryOptions> = OrArray, Options, OppositeRelationAndFK>>; type NestedDeleteInput, Field extends RelationFields, Options extends QueryOptions> = FieldIsArray extends true ? OrArray, Options>, true> : boolean | WhereInput, Options>; type NestedDeleteManyInput, Field extends RelationFields, Options extends QueryOptions> = OrArray, Options, true>>; type GetProcedureNames = Schema extends { procedures: Record; } ? keyof Schema['procedures'] : never; type GetProcedureParams> = Schema extends { procedures: Record; } ? Schema['procedures'][ProcName]['params'] : never; type GetProcedure> = Schema extends { procedures: Record; } ? Schema['procedures'][ProcName] : never; type _OptionalProcedureParamNames = keyof { [K in keyof Params as Params[K] extends { optional: true; } ? K : never]: K }; type _RequiredProcedureParamNames = keyof { [K in keyof Params as Params[K] extends { optional: true; } ? never : K]: K }; type _HasRequiredProcedureParams = _RequiredProcedureParamNames extends never ? false : true; type MapProcedureArgsObject = Simplify }, _OptionalProcedureParamNames>>; type ProcedureEnvelope, Params = GetProcedureParams> = keyof Params extends never ? { args?: Record; } : _HasRequiredProcedureParams extends true ? { args: MapProcedureArgsObject; } : { args?: MapProcedureArgsObject; }; type ProcedureHandlerCtx> = { client: ClientContract; } & ProcedureEnvelope; /** * Shape of a procedure's runtime function. */ type ProcedureFunc> = (...args: _HasRequiredProcedureParams> extends true ? [input: ProcedureEnvelope] : [input?: ProcedureEnvelope]) => MaybePromise>>; /** * Signature for procedure handlers configured via client options. */ type ProcedureHandlerFunc> = (ctx: ProcedureHandlerCtx) => MaybePromise>>; type MapProcedureReturn = Proc extends { returnType: infer R; } ? Proc extends { returnArray: true; } ? Array> : MapType : never; type MapProcedureParam = P extends { type: infer U; } ? OrUndefinedIf

> : MapType, P extends { optional: true; } ? true : false> : never; type NonOwnedRelationFields> = keyof { [Key in RelationFields as GetModelField['relation'] extends { references: readonly unknown[]; } ? never : Key]: true }; type HasToManyRelations> = keyof { [Key in RelationFields as FieldIsArray extends true ? Key : never]: true } extends never ? false : true; type EnumValue> = GetEnum[keyof GetEnum]; type MapType = T extends keyof TypeMap ? TypeMap[T] : T extends GetModels ? ModelResult : T extends GetTypeDefs ? TypeDefResult : T extends GetEnums ? EnumValue : unknown; type ProviderSupportsDistinct = Schema['provider']['type'] extends 'postgresql' ? true : false; type ProviderSupportsFuzzy = Schema['provider']['type'] extends 'postgresql' ? true : false; type ProviderSupportsFullText = Schema['provider']['type'] extends 'postgresql' ? true : false; /** * Extracts extended query args for a specific operation. */ type ExtractExtQueryArgs = (Operation extends keyof ExtQueryArgs ? ExtQueryArgs[Operation] : {}) & ('$create' extends keyof ExtQueryArgs ? Operation extends CoreCreateOperations ? ExtQueryArgs['$create'] : {} : {}) & ('$read' extends keyof ExtQueryArgs ? (Operation extends CoreReadOperations ? ExtQueryArgs['$read'] : {}) : {}) & ('$update' extends keyof ExtQueryArgs ? Operation extends CoreUpdateOperations ? ExtQueryArgs['$update'] : {} : {}) & ('$delete' extends keyof ExtQueryArgs ? Operation extends CoreDeleteOperations ? ExtQueryArgs['$delete'] : {} : {}) & ('$all' extends keyof ExtQueryArgs ? ExtQueryArgs['$all'] : {}); /** * Extracts extended result field types for a specific model from ExtResult. * Maps `{ needs, compute }` definitions to `{ fieldName: ReturnType }`. * When ExtResult is `{}`, this resolves to `{}` (no-op for intersection). */ type ExtractExtResult = Uncapitalize extends keyof ExtResult ? { [K in keyof ExtResult[Uncapitalize]]: ExtResult[Uncapitalize][K] extends { compute: (...args: any[]) => infer R; } ? R : never } : {}; /** * Extracts extended result field names as optional boolean keys for use in select/omit inputs. * When ExtResult is `{}`, this resolves to `{}` (no-op for intersection). */ type ExtResultSelectOmitFields = keyof ExtResult extends never ? {} : Uncapitalize extends keyof ExtResult ? { [K in keyof ExtResult[Uncapitalize]]?: boolean } : {}; type TruthyKeys = { [K in Keys]: K extends keyof S ? (S[K] extends false | undefined ? never : K) : never }[Keys]; /** * Select/omit-aware version of ExtractExtResult. * - If T has `select`, only includes ext result fields that are explicitly selected. * - If T has `omit`, excludes ext result fields that are explicitly omitted. * - Otherwise, includes all ext result fields. */ type SelectAwareExtResult = keyof ExtResult extends never ? {} : T extends { select: infer S; } ? S extends null | undefined ? ExtractExtResult : Pick, TruthyKeys>>> : T extends { omit: infer O; } ? O extends null | undefined ? ExtractExtResult : Omit, TruthyKeys>>> : ExtractExtResult; //#endregion //#region src/client/diagnostics.d.ts /** * Zod schema cache statistics. */ interface ZodCacheStats { /** * Number of cached Zod schemas. */ size: number; /** * Keys of the cached Zod schemas. */ keys: string[]; } /** * Information about a query, used for diagnostics. */ interface QueryInfo { /** * Time when the query started. */ startedAt: Date; /** * Duration of the query in milliseconds. */ durationMs: number; /** * SQL statement of the query. */ sql: string; } /** * ZenStackClient diagnostics. */ interface Diagnostics { /** * Statistics about the Zod schemas (used for query args validation) cache. */ zodCache: ZodCacheStats; /** * Slow queries. */ slowQueries: QueryInfo[]; } //#endregion //#region src/client/promise.d.ts /** * A promise that only executes when it's awaited or .then() is called. */ interface ZenStackPromise extends Promise { [Symbol.toStringTag]: 'ZenStackPromise'; } //#endregion //#region src/client/contract.d.ts type TransactionUnsupportedMethods = (typeof TRANSACTION_UNSUPPORTED_METHODS)[number]; /** * Transaction isolation levels. */ declare enum TransactionIsolationLevel { ReadUncommitted = "read uncommitted", ReadCommitted = "read committed", RepeatableRead = "repeatable read", Serializable = "serializable", Snapshot = "snapshot" } /** * Symbol used as a type-only key on `ClientContract` to brand the `ExtQueryArgs` * generic slot. Hidden from member-access autocomplete since symbol keys are * not surfaced. Consumed by `InferExtQueryArgs` to recover the slot. * @internal */ declare const ExtQueryArgsMarker: unique symbol; /** * Symbol used as a type-only key on `ClientContract` to brand the `ExtResult` * generic slot. Consumed by `InferExtResult` to recover the slot. * @internal */ declare const ExtResultMarker: unique symbol; /** * ZenStack client interface. * * Note: this alias resolves to an intersection, so it cannot carry variance annotations itself * (TS2637). It doesn't need them - measuring its variance recurses into {@link ModelOperations}, * whose annotations short-circuit the expensive cascade. See {@link CommonModelOperations}. */ type ClientContract = ClientOptions, ExtQueryArgs extends ExtQueryArgsBase = {}, ExtClientMembers extends ExtClientMembersBase = {}, ExtResult extends ExtResultBase = {}> = { /** * The schema definition. */ readonly $schema: Schema; /** * The client options. */ readonly $options: Options; /** @internal type-only brand carrying the `ExtQueryArgs` slot for inference. */ readonly [ExtQueryArgsMarker]?: ExtQueryArgs; /** @internal type-only brand carrying the `ExtResult` slot for inference. */ readonly [ExtResultMarker]?: ExtResult; /** * Executes a prepared raw query and returns the number of affected rows. * @example * ``` * const result = await db.$executeRaw`UPDATE User SET cool = ${true} WHERE email = ${'user@email.com'};` * ``` */ $executeRaw(query: TemplateStringsArray, ...values: any[]): ZenStackPromise; /** * Executes a raw query and returns the number of affected rows. * This method is susceptible to SQL injections. * @example * ``` * const result = await db.$executeRawUnsafe('UPDATE User SET cool = $1 WHERE email = $2 ;', true, 'user@email.com') * ``` */ $executeRawUnsafe(query: string, ...values: any[]): ZenStackPromise; /** * Performs a prepared raw query and returns the `SELECT` data. * @example * ``` * const result = await db.$queryRaw`SELECT * FROM User WHERE id = ${1} OR email = ${'user@email.com'};` * ``` */ $queryRaw(query: TemplateStringsArray, ...values: any[]): ZenStackPromise; /** * Performs a raw query and returns the `SELECT` data. * This method is susceptible to SQL injections. * @example * ``` * const result = await db.$queryRawUnsafe('SELECT * FROM User WHERE id = $1 OR email = $2;', 1, 'user@email.com') * ``` */ $queryRawUnsafe(query: string, ...values: any[]): ZenStackPromise; /** * The current user identity. If the client is not bound to any user context, returns `undefined`. */ get $auth(): AuthType | undefined; /** * Returns a new client bound to the specified user identity. The original client remains unchanged. * Pass `undefined` to return a client without any user context. * * @example * ``` * const userClient = db.$setAuth({ id: 'user-id' }); * ``` */ $setAuth(auth: AuthType | undefined): ClientContract; /** * Returns a new client with new options applied. The original client remains unchanged. * * @example * ``` * const dbNoValidation = db.$setOptions({ ...db.$options, validateInput: false }); * ``` */ $setOptions>(options: NewOptions): ClientContract; /** * Returns a new client enabling/disabling query args validation. The original client remains unchanged. * * @deprecated Use {@link $setOptions} instead. */ $setInputValidation(enable: boolean): ClientContract; /** * The Kysely query builder instance. * * @example * ``` * db.$qb.selectFrom('User').selectAll().where('id', '=', 1).execute(); * ``` */ readonly $qb: ToKysely; /** * The raw Kysely query builder without any ZenStack enhancements. */ readonly $qbRaw: AnyKysely; /** * Starts an interactive transaction. * * @example * ``` * await db.$transaction(async (tx) => { * const user = await tx.user.update({ where: { id: 1 }, data: { name: 'Alice' } }); * const post = await tx.post.create({ data: { title: 'Hello World', authorId: user.id } }); * return { user, posts: [post] }; * ``` */ $transaction(callback: (tx: TransactionClientContract) => Promise, options?: { isolationLevel?: TransactionIsolationLevel; }): Promise; /** * Starts a sequential transaction that runs the provided operations in order. * * @example * ``` * await db.$transaction([ * db.user.update({ where: { id: 1 }, data: { name: 'Alice' } }), * db.post.create({ data: { title: 'Hello World', authorId: 1 } }), * ]); */ $transaction

[]>(arg: [...P], options?: { isolationLevel?: TransactionIsolationLevel; }): Promise>; /** * Returns a new client with the specified plugin installed. The original client remains unchanged. * * @see {@link https://zenstack.dev/docs/orm/plugins/|Plugin Documentation} */ $use = {}, _R = {}>(plugin: RuntimePlugin & { result?: ExtResultInferenceArgs; }): ClientContract; /** * Returns a new client with the specified plugin removed. The original client remains unchanged. */ $unuse(pluginId: string): ClientContract; /** * Returns a new client with all plugins removed. The original client remains unchanged. */ $unuseAll(): ClientContract; /** * Eagerly connects to the database. */ $connect(): Promise; /** * Explicitly disconnects from the database. */ $disconnect(): Promise; /** * Factory for creating zod schemas to validate query args. */ get $zod(): ZodSchemaFactory, ExtQueryArgs>; /** * Pushes the schema to the database. For testing purposes only. * @private */ $pushSchema(): Promise; /** * Returns diagnostics information such as cache and slow query statistics. */ get $diagnostics(): Promise; } & { [Key in GetSlicedModels> as Uncapitalize]: ModelOperations, ExtQueryArgs, ExtResult> } & ProcedureOperations & ExtClientMembers; /** * The contract for a client in a transaction. */ type TransactionClientContract, ExtQueryArgs extends ExtQueryArgsBase, ExtClientMembers extends ExtClientMembersBase, ExtResult extends ExtResultBase = {}> = Omit, TransactionUnsupportedMethods>; type ProcedureOperations = ClientOptions> = Schema['procedures'] extends Record ? { /** * Custom procedures. */ $procs: { [Key in GetSlicedProcedures]: ProcedureFunc }; } : {}; /** * Creates a new ZenStack client instance. */ interface ClientConstructor { new = ClientOptions>(schema: Schema, options: Options): ClientContract; } /** * CRUD operations. */ type CRUD = 'create' | 'read' | 'update' | 'delete'; /** * Extended CRUD operations including 'post-update'. */ type CRUD_EXT = CRUD | 'post-update'; /** * CRUD operations. */ declare const CRUD: readonly ["create", "read", "update", "delete"]; /** * Extended CRUD operations including 'post-update'. */ declare const CRUD_EXT: readonly ["create", "read", "update", "delete", "post-update"]; type SliceOperations, Schema extends SchemaDef, Model extends GetModels, Options extends QueryOptions> = Omit<{ [Key in keyof T as Key extends GetSlicedOperations ? Key : never]: T[Key] }, ModelAllowsCreate extends true ? never : OperationsRequiringCreate>; type AllModelOperations, Options extends QueryOptions, ExtQueryArgs extends ExtQueryArgsBase, ExtResult extends ExtResultBase = {}> = CommonModelOperations & (Schema['provider']['type'] extends 'mysql' ? {} : { /** * Creates multiple entities and returns them. * @param args - create args. See {@link createMany} for input. Use * `select` and `omit` to control the fields returned. * @returns the created entities * * @example * ```ts * // create multiple entities and return selected fields * await db.user.createManyAndReturn({ * data: [ * { name: 'Alex', email: 'alex@zenstack.dev' }, * { name: 'John', email: 'john@zenstack.dev' } * ], * select: { id: true, email: true } * }); * ``` */ createManyAndReturn>(args?: SelectSubset>): ZenStackPromise>; /** * Updates multiple entities and returns them. * @param args - update args. Only scalar fields are allowed for data. * @returns the updated entities * * @example * ```ts * // update many entities and return selected fields * await db.user.updateManyAndReturn({ * where: { email: { endsWith: '@zenstack.dev' } }, * data: { role: 'ADMIN' }, * select: { id: true, email: true } * }); // result: `Array<{ id: string; email: string }>` * * // limit the number of updated entities * await db.user.updateManyAndReturn({ * where: { email: { endsWith: '@zenstack.dev' } }, * data: { role: 'ADMIN' }, * limit: 10 * }); * ``` */ updateManyAndReturn>(args: Subset>): ZenStackPromise>; }); type CommonModelOperations, in out Options extends QueryOptions, in out ExtQueryArgs extends ExtQueryArgsBase, out ExtResult extends ExtResultBase = {}> = { /** * Returns a list of entities. * @param args - query args * @returns a list of entities * * @example * ```ts * // find all users and return all scalar fields * await db.user.findMany(); * * // find all users with name 'Alex' * await db.user.findMany({ * where: { * name: 'Alex' * } * }); * * // select fields * await db.user.findMany({ * select: { * name: true, * email: true, * } * }); // result: `Array<{ name: string, email: string }>` * * // omit fields * await db.user.findMany({ * omit: { * name: true, * } * }); // result: `Array<{ id: number; email: string; ... }>` * * // include relations (and all scalar fields) * await db.user.findMany({ * include: { * posts: true, * } * }); // result: `Array<{ ...; posts: Post[] }>` * * // include relations with filter * await db.user.findMany({ * include: { * posts: { * where: { * published: true * } * } * } * }); * * // pagination and sorting * await db.user.findMany({ * skip: 10, * take: 10, * orderBy: [{ name: 'asc' }, { email: 'desc' }], * }); * * // pagination with cursor (https://www.prisma.io/docs/orm/prisma-client/queries/pagination#cursor-based-pagination) * await db.user.findMany({ * cursor: { id: 10 }, * skip: 1, * take: 10, * orderBy: { id: 'asc' }, * }); * * // distinct * await db.user.findMany({ * distinct: ['name'] * }); * * // count all relations * await db.user.findMany({ * _count: true, * }); // result: `{ _count: { posts: number; ... } }` * * // count selected relations * await db.user.findMany({ * _count: { select: { posts: true } }, * }); // result: `{ _count: { posts: number } }` * ``` */ findMany>(args?: SelectSubset>): ZenStackPromise>; /** * Returns a uniquely identified entity. * @param args - query args * @returns a single entity or null if not found * @see {@link findMany} */ findUnique>(args: SelectSubset>): ZenStackPromise>; /** * Returns a uniquely identified entity or throws `NotFoundError` if not found. * @param args - query args * @returns a single entity * @see {@link findMany} */ findUniqueOrThrow>(args: SelectSubset>): ZenStackPromise>; /** * Returns the first entity. * @param args - query args * @returns a single entity or null if not found * @see {@link findMany} */ findFirst>(args?: SelectSubset>): ZenStackPromise>; /** * Returns the first entity or throws `NotFoundError` if not found. * @param args - query args * @returns a single entity * @see {@link findMany} */ findFirstOrThrow>(args?: SelectSubset>): ZenStackPromise>; /** * Creates a new entity. * @param args - create args * @returns the created entity * * @example * ```ts * // simple create * await db.user.create({ * data: { name: 'Alex', email: 'alex@zenstack.dev' } * }); * * // nested create with relation * await db.user.create({ * data: { * email: 'alex@zenstack.dev', * posts: { create: { title: 'Hello World' } } * } * }); * * // you can use `select`, `omit`, and `include` to control * // the fields returned by the query, as with `findMany` * await db.user.create({ * data: { * email: 'alex@zenstack.dev', * posts: { create: { title: 'Hello World' } } * }, * include: { posts: true } * }); // result: `{ id: number; posts: Post[] }` * * // connect relations * await db.user.create({ * data: { * email: 'alex@zenstack.dev', * posts: { connect: { id: 1 } } * } * }); * * // connect relations, and create if not found * await db.user.create({ * data: { * email: 'alex@zenstack.dev', * posts: { * connectOrCreate: { * where: { id: 1 }, * create: { title: 'Hello World' } * } * } * } * }); * ``` */ create>(args: SelectSubset>): ZenStackPromise>; /** * Creates multiple entities. Only scalar fields are allowed. * @param args - create args * @returns count of created entities: `{ count: number }` * * @example * ```ts * // create multiple entities * await db.user.createMany({ * data: [ * { name: 'Alex', email: 'alex@zenstack.dev' }, * { name: 'John', email: 'john@zenstack.dev' } * ] * }); * * // skip items that cause unique constraint violation * await db.user.createMany({ * data: [ * { name: 'Alex', email: 'alex@zenstack.dev' }, * { name: 'John', email: 'john@zenstack.dev' } * ], * skipDuplicates: true * }); * ``` */ createMany>(args?: SelectSubset>): ZenStackPromise>; /** * Updates a uniquely identified entity. * @param args - update args. See {@link findMany} for how to control * fields and relations returned. * @returns the updated entity. Throws `NotFoundError` if the entity is not found. * * @example * ```ts * // update fields * await db.user.update({ * where: { id: 1 }, * data: { name: 'Alex' } * }); * * // connect a relation * await db.user.update({ * where: { id: 1 }, * data: { posts: { connect: { id: 1 } } } * }); * * // connect relation, and create if not found * await db.user.update({ * where: { id: 1 }, * data: { * posts: { * connectOrCreate: { * where: { id: 1 }, * create: { title: 'Hello World' } * } * } * } * }); * * // create many related entities (only available for one-to-many relations) * await db.user.update({ * where: { id: 1 }, * data: { * posts: { * createMany: { * data: [{ title: 'Hello World' }, { title: 'Hello World 2' }], * } * } * } * }); * * // disconnect a one-to-many relation * await db.user.update({ * where: { id: 1 }, * data: { posts: { disconnect: { id: 1 } } } * }); * * // disconnect a one-to-one relation * await db.user.update({ * where: { id: 1 }, * data: { profile: { disconnect: true } } * }); * * // replace a relation (only available for one-to-many relations) * await db.user.update({ * where: { id: 1 }, * data: { * posts: { * set: [{ id: 1 }, { id: 2 }] * } * } * }); * * // update a relation * await db.user.update({ * where: { id: 1 }, * data: { * posts: { * update: { where: { id: 1 }, data: { title: 'Hello World' } } * } * } * }); * * // upsert a relation * await db.user.update({ * where: { id: 1 }, * data: { * posts: { * upsert: { * where: { id: 1 }, * create: { title: 'Hello World' }, * update: { title: 'Hello World' } * } * } * } * }); * * // update many related entities (only available for one-to-many relations) * await db.user.update({ * where: { id: 1 }, * data: { * posts: { * updateMany: { * where: { published: true }, * data: { title: 'Hello World' } * } * } * } * }); * * // delete a one-to-many relation * await db.user.update({ * where: { id: 1 }, * data: { posts: { delete: { id: 1 } } } * }); * * // delete a one-to-one relation * await db.user.update({ * where: { id: 1 }, * data: { profile: { delete: true } } * }); * ``` */ update>(args: SelectSubset>): ZenStackPromise>; /** * Updates multiple entities. * @param args - update args. Only scalar fields are allowed for data. * @returns count of updated entities: `{ count: number }` * * @example * ```ts * // update many entities * await db.user.updateMany({ * where: { email: { endsWith: '@zenstack.dev' } }, * data: { role: 'ADMIN' } * }); * * // limit the number of updated entities * await db.user.updateMany({ * where: { email: { endsWith: '@zenstack.dev' } }, * data: { role: 'ADMIN' }, * limit: 10 * }); */ updateMany>(args: Subset>): ZenStackPromise>; /** * Creates or updates an entity. * @param args - upsert args * @returns the upserted entity * * @example * ```ts * // upsert an entity * await db.user.upsert({ * // `where` clause is used to find the entity * where: { id: 1 }, * // `create` clause is used if the entity is not found * create: { email: 'alex@zenstack.dev', name: 'Alex' }, * // `update` clause is used if the entity is found * update: { name: 'Alex-new' }, * // `select` and `omit` can be used to control the returned fields * ... * }); * ``` */ upsert>(args: SelectSubset>): ZenStackPromise>; /** * Deletes a uniquely identifiable entity. * @param args - delete args * @returns the deleted entity. Throws `NotFoundError` if the entity is not found. * * @example * ```ts * // delete an entity * await db.user.delete({ * where: { id: 1 } * }); * * // delete an entity and return selected fields * await db.user.delete({ * where: { id: 1 }, * select: { id: true, email: true } * }); // result: `{ id: string; email: string }` * ``` */ delete>(args: SelectSubset>): ZenStackPromise>; /** * Deletes multiple entities. * @param args - delete args * @returns count of deleted entities: `{ count: number }` * * @example * ```ts * // delete many entities * await db.user.deleteMany({ * where: { email: { endsWith: '@zenstack.dev' } } * }); * * // limit the number of deleted entities * await db.user.deleteMany({ * where: { email: { endsWith: '@zenstack.dev' } }, * limit: 10 * }); * ``` */ deleteMany>(args?: Subset>): ZenStackPromise>; /** * Counts rows or field values. * @param args - count args * @returns `number`, or an object containing count of selected relations * * @example * ```ts * // count all * await db.user.count(); * * // count with a filter * await db.user.count({ where: { email: { endsWith: '@zenstack.dev' } } }); * * // count rows and field values * await db.user.count({ * select: { _all: true, email: true } * }); // result: `{ _all: number, email: number }` */ count>(args?: Subset>): ZenStackPromise>>; /** * Aggregates rows. * @param args - aggregation args * @returns an object containing aggregated values * * @example * ```ts * // aggregate rows * await db.profile.aggregate({ * where: { email: { endsWith: '@zenstack.dev' } }, * _count: true, * _avg: { age: true }, * _sum: { age: true }, * _min: { age: true }, * _max: { age: true } * }); // result: `{ _count: number, _avg: { age: number }, ... }` */ aggregate>(args: Subset>): ZenStackPromise>>; /** * Groups rows by columns. * @param args - groupBy args * @returns an object containing grouped values * * @example * ```ts * // group by a field * await db.profile.groupBy({ * by: 'country', * _count: true * }); // result: `Array<{ country: string, _count: number }>` * * // group by multiple fields * await db.profile.groupBy({ * by: ['country', 'city'], * _count: true * }); // result: `Array<{ country: string, city: string, _count: number }>` * * // group by with sorting, the `orderBy` fields must be either an aggregation * // or a field used in the `by` list * await db.profile.groupBy({ * by: 'country', * orderBy: { country: 'desc' } * }); * * // group by with having (post-aggregation filter), the fields used in `having` must * // be either an aggregation, or a field used in the `by` list * await db.profile.groupBy({ * by: 'country', * having: { country: 'US', age: { _avg: { gte: 18 } } } * }); */ groupBy>(args: Subset>): ZenStackPromise>>; /** * Checks if an entity exists. * @param args - exists args * @returns whether a matching entity was found * * @example * ```ts * // check if a user exists * await db.user.exists({ * where: { id: 1 }, * }); // result: `boolean` * * // check with a relation * await db.user.exists({ * where: { posts: { some: { published: true } } }, * }); // result: `boolean` */ exists>(args?: Subset>): ZenStackPromise>; }; type OperationsRequiringCreate = 'create' | 'createMany' | 'createManyAndReturn' | 'upsert'; type ModelOperations, in out Options extends QueryOptions = ClientOptions, in out ExtQueryArgs extends ExtQueryArgsBase = {}, out ExtResult extends ExtResultBase = {}> = SliceOperations, Schema, Model, Options>; /** * Type for auth context that includes both scalar and relation fields. * Relations are recursively included to allow nested auth data like { user: { profile: { ... } } } */ type AuthModelType> = Partial> & { [Key in RelationFields]?: FieldIsArray extends true ? AuthModelType>[] : AuthModelType> }; type AuthType = Schema['authType'] extends GetModels ? AuthModelType : Schema['authType'] extends GetTypeDefs ? TypeDefResult : Record; //#endregion //#region src/client/zod/factory.d.ts /** * Create a factory for generating Zod schemas to validate ORM query inputs. */ declare function createQuerySchemaFactory, ExtQueryArgs extends ExtQueryArgsBase = {}>(client: ClientContract): ZodSchemaFactory; /** * Create a factory for generating Zod schemas to validate ORM query inputs. */ declare function createQuerySchemaFactory = ClientOptions, ExtQueryArgs extends ExtQueryArgsBase = {}>(schema: Schema, options?: Options): ZodSchemaFactory; /** * Create a factory using only query options (e.g. slicing) without a full client config. */ declare function createQuerySchemaFactory(schema: Schema, options?: QueryOptions): ZodSchemaFactory; /** * Options for creating Zod schemas. */ type CreateSchemaOptions = { /** * Controls the depth of relation nesting in the generated schema. Default is unlimited. */ relationDepth?: number; }; /** * Factory class responsible for creating and caching Zod schemas for ORM input validation. */ declare class ZodSchemaFactory = ClientOptions, ExtQueryArgs extends ExtQueryArgsBase = {}> { private readonly schemaCache; private readonly schemaRegistry; private readonly allFilterKinds; private readonly schema; private readonly options; private readonly extraValidationsEnabled; constructor(client: ClientContract); constructor(schema: Schema, options?: Options); private get plugins(); /** * Returns model field entries, excluding Unsupported fields. */ private getModelFields; private shouldIncludeRelations; private nextOptions; private getCache; private setCache; /** * Builds a suffix to append to schema IDs when filter variants differ from defaults. * Ensures different combinations of optional, array, and allowedFilterKinds produce distinct registry entries. */ private filterSchemaSuffix; /** * Registers a schema in the registry under the given id. * Safe to call multiple times with the same id: first registration wins, subsequent ones are silently skipped. */ private registerSchema; /** * Returns a JSON Schema document containing all registered Zod schemas as named definitions. * The returned object has the shape `{ schemas: { [id]: jsonSchema } }`. * * Eagerly builds all top-level schemas for every model so the registry is fully populated * before serialization. */ toJSONSchema(): { schemas: Record; }; get cacheStats(): { size: number; keys: string[]; }; makeFindUniqueSchema>(model: Model, options?: CreateSchemaOptions): ZodType>; makeFindFirstSchema>(model: Model, options?: CreateSchemaOptions): ZodType | undefined>; makeFindManySchema>(model: Model, options?: CreateSchemaOptions): ZodType | undefined>; private makeFindSchema; makeExistsSchema>(model: Model, options?: CreateSchemaOptions): ZodType | undefined>; private makeScalarSchema; private makeEnumSchema; private makeTypeDefSchema; makeWhereSchema(model: string, unique: boolean, withoutRelationFields?: boolean, withAggregations?: boolean, options?: CreateSchemaOptions): ZodType; private makeTypedJsonFilterSchema; private makeNullableTypedJsonMutationSchema; private isTypeDefType; private makeEnumFilterSchema; private makeArrayFilterSchema; private internalMakeArrayFilterSchema; private makePrimitiveFilterSchema; private makeJsonValueSchema; private makeJsonFilterSchema; private makeDateTimeValueSchema; private makeDateTimeFilterSchema; private makeBooleanFilterSchema; private makeBytesFilterSchema; private makeCommonPrimitiveFilterComponents; private makeCommonPrimitiveFilterSchema; private makeNumberFilterSchema; private makeStringFilterSchema; private makeStringModeSchema; private makeFuzzyFilterSchema; private makeFullTextFilterSchema; private makeSelectSchema; private makeCountSelectionSchema; private makeRelationSelectIncludeSchema; /** * Determines whether a field is configured to be omitted at the schema or client-options level * (query-level omit is excluded as it's mutually exclusive with `select`). */ private isFieldOmittedByConfig; private makeOmitSchema; private addExtResultFields; private makeIncludeSchema; private makeOrderBySchema; private makeDistinctSchema; private makeCursorSchema; makeCreateSchema>(model: Model, options?: CreateSchemaOptions): ZodType>; makeCreateManySchema>(model: Model, options?: CreateSchemaOptions): ZodType>; makeCreateManyAndReturnSchema>(model: Model, options?: CreateSchemaOptions): ZodType>; private makeCreateDataSchema; private makeRelationManipulationSchema; private makeSetDataSchema; private makeConnectDataSchema; private makeDisconnectDataSchema; private makeDeleteRelationDataSchema; private makeConnectOrCreateDataSchema; private makeCreateManyPayloadSchema; makeUpdateSchema>(model: Model, options?: CreateSchemaOptions): ZodType>; makeUpdateManySchema>(model: Model, options?: CreateSchemaOptions): ZodType>; makeUpdateManyAndReturnSchema>(model: Model, options?: CreateSchemaOptions): ZodType>; makeUpsertSchema>(model: Model, options?: CreateSchemaOptions): ZodType>; private makeUpdateDataSchema; makeDeleteSchema>(model: Model, options?: CreateSchemaOptions): ZodType>; makeDeleteManySchema>(model: Model, options?: CreateSchemaOptions): ZodType | undefined>; makeCountSchema>(model: Model, options?: CreateSchemaOptions): ZodType | undefined>; private makeCountAggregateInputSchema; makeAggregateSchema>(model: Model, options?: CreateSchemaOptions): ZodType>; private makeSumAvgInputSchema; private makeMinMaxInputSchema; makeGroupBySchema>(model: Model, options?: CreateSchemaOptions): ZodType>; private onlyAggregationFields; private makeHavingSchema; makeProcedureArgsSchema(procName: string): ZodType; makeProcedureParamSchema(param: { type: string; array?: boolean; optional?: boolean; }, _options?: CreateSchemaOptions): ZodType; private mergePluginArgsSchema; private getPluginExtQueryArgsSchema; private makeSkipSchema; private makeTakeSchema; private refineForSelectIncludeMutuallyExclusive; private refineForSelectOmitMutuallyExclusive; private refineForSelectHasTruthyField; private nullableIf; private orArray; private isNumericField; private get providerSupportsCaseSensitivity(); private get providerSupportsFullTextSearch(); private get providerSupportsFuzzySearch(); /** * Gets the effective set of allowed FilterKind values for a specific model and field. * Respects the precedence: model[field] > model.$all > $all[field] > $all.$all. */ private getEffectiveFilterKinds; /** * Computes the effective set of filter kinds based on inclusion and exclusion lists. */ private computeFilterKinds; /** * Filters operators based on allowed filter kinds. */ private trimFilterOperators; private createUnionFilterSchema; private canCreateModel; private isModelAllowed; private isProcedureAllowed; } //#endregion //#region src/client/client-impl.d.ts /** * ZenStack ORM client. */ declare const ZenStackClient: ClientConstructor; //#endregion //#region src/client/crud/dialects/index.d.ts declare function getCrudDialect(schema: Schema, options: ClientOptions): BaseCrudDialect; //#endregion //#region src/client/errors.d.ts /** * Reason code for ORM errors. */ declare enum ORMErrorReason { /** * ORM client configuration error. */ CONFIG_ERROR = "config-error", /** * Invalid input error. */ INVALID_INPUT = "invalid-input", /** * The specified record was not found. */ NOT_FOUND = "not-found", /** * Operation is rejected by access policy. */ REJECTED_BY_POLICY = "rejected-by-policy", /** * Error was thrown by the underlying database driver. */ DB_QUERY_ERROR = "db-query-error", /** * The requested operation is not supported. */ NOT_SUPPORTED = "not-supported", /** * An internal error occurred. */ INTERNAL_ERROR = "internal-error" } /** * Reason code for policy rejection. */ declare enum RejectedByPolicyReason { /** * Rejected because the operation is not allowed by policy. */ NO_ACCESS = "no-access", /** * Rejected because the result cannot be read back after mutation due to policy. */ CANNOT_READ_BACK = "cannot-read-back", /** * Other reasons. */ OTHER = "other" } /** * ZenStack ORM error. */ declare class ORMError extends Error { reason: ORMErrorReason; constructor(reason: ORMErrorReason, message?: string, options?: ErrorOptions); /** * The name of the model that the error pertains to. */ model?: string; /** * The error code given by the underlying database driver. */ dbErrorCode?: unknown; /** * The error message given by the underlying database driver. */ dbErrorMessage?: string; /** * The reason code for policy rejection. Only available when `reason` is `REJECTED_BY_POLICY`. */ rejectedByPolicyReason?: RejectedByPolicyReason; /** * The SQL query that was executed. Only available when `reason` is `DB_QUERY_ERROR`. */ sql?: string; /** * The parameters used in the SQL query. Only available when `reason` is `DB_QUERY_ERROR`. */ sqlParams?: readonly unknown[]; } declare namespace query_utils_d_exports { export { ManyToManyJoinTableEndpoints, TEMP_ALIAS_PREFIX, aggregate, buildJoinPairs, ensureArray, extractFieldName, extractIdFields, extractModelName, fieldHasDefaultValue, flattenCompoundUniqueFilters, getDelegateDescendantModels, getDelegateDiscriminatorValue, getDiscriminatorField, getEnum, getField, getIdFields, getIdValues, getManyToManyJoinTable, getManyToManyRelation, getModel, getModelFields, getRelationForeignKeyFieldPairs, getTypeDef, getUniqueFields, hasModel, isEnum, isForeignKeyField, isInheritedField, isRelationField, isScalarField, isTypeDef, isUnsupportedField, makeDefaultOrderBy, requireField, requireIdFields, requireModel, requireTypeDef, stripAlias, tmpAlias }; } declare function hasModel(schema: SchemaDef, model: string): boolean; declare function getModel(schema: SchemaDef, model: string): ModelDef | undefined; declare function getTypeDef(schema: SchemaDef, type: string): _$_zenstackhq_schema0.TypeDefDef | undefined; declare function requireModel(schema: SchemaDef, model: string): ModelDef; declare function requireTypeDef(schema: SchemaDef, type: string): _$_zenstackhq_schema0.TypeDefDef; declare function getField(schema: SchemaDef, model: string, field: string): FieldDef | undefined; declare function requireField(schema: SchemaDef, modelOrType: string, field: string): FieldDef; /** * Gets all model fields, by default non-relation, non-computed, non-inherited, non-unsupported fields only. */ declare function getModelFields(schema: SchemaDef, model: string, options?: { relations?: boolean; computed?: boolean; inherited?: boolean; unsupported?: boolean; }): FieldDef[]; /** * Checks if a field is of `Unsupported` type. */ declare function isUnsupportedField(fieldDef: FieldDef): boolean; declare function getIdFields(schema: SchemaDef, model: GetModels): readonly string[] | undefined; declare function requireIdFields(schema: SchemaDef, model: string): readonly string[]; declare function getRelationForeignKeyFieldPairs(schema: SchemaDef, model: string, relationField: string): { keyPairs: { fk: string; pk: string; }[]; ownedByModel: boolean; }; declare function isScalarField(schema: SchemaDef, model: string, field: string): boolean; declare function isForeignKeyField(schema: SchemaDef, model: string, field: string): boolean; declare function isRelationField(schema: SchemaDef, model: string, field: string): boolean; declare function isInheritedField(schema: SchemaDef, model: string, field: string): boolean; declare function getUniqueFields(schema: SchemaDef, model: string): ({ name: string; def: FieldDef; } | { name: string; defs: Record; })[]; declare function getIdValues(schema: SchemaDef, model: string, data: any): Record; declare function fieldHasDefaultValue(fieldDef: FieldDef): boolean | _$_zenstackhq_schema0.UpdatedAtInfo | undefined; declare function isEnum(schema: SchemaDef, type: string): boolean; declare function getEnum(schema: SchemaDef, type: string): _$_zenstackhq_schema0.EnumDef | undefined; declare function isTypeDef(schema: SchemaDef, type: string): boolean; declare function buildJoinPairs(schema: SchemaDef, model: string, modelAlias: string, relationField: string, relationModelAlias: string): [string, string][]; declare function makeDefaultOrderBy(schema: SchemaDef, model: string): { readonly [x: string]: "asc"; }[]; declare function getManyToManyRelation(schema: SchemaDef, model: string, field: string): { parentFkName: string; parentPKName: string; otherModel: string; otherField: string; otherFkName: string; otherPKName: string; joinTable: string; } | undefined; /** * Endpoints of an implicit many-to-many relation, identified by its join table name. */ interface ManyToManyJoinTableEndpoints { model: string; field: string; otherModel: string; otherField: string; } /** * Resolve the relation endpoints for an implicit many-to-many join table by its table * name, or `undefined` if the table is not an implicit m2m join table. The join-table * index is built once per schema (single pass) and reused, making this an O(1) lookup. * See issue #2715. */ declare function getManyToManyJoinTable(schema: SchemaDef, joinTableName: string): ManyToManyJoinTableEndpoints | undefined; /** * Convert filter like `{ id1_id2: { id1: 1, id2: 1 } }` to `{ id1: 1, id2: 1 }` */ declare function flattenCompoundUniqueFilters(schema: SchemaDef, model: string, filter: unknown): any; declare function ensureArray(value: T | T[]): T[]; declare function extractIdFields(entity: any, schema: SchemaDef, model: string): { [k: string]: unknown; }; declare function getDiscriminatorField(schema: SchemaDef, model: string): string | undefined; declare function getDelegateDiscriminatorValue(schema: SchemaDef, model: string): string; declare function getDelegateDescendantModels(schema: SchemaDef, model: string, collected?: Set): ModelDef[]; declare function aggregate(eb: ExpressionBuilder, expr: Expression, op: AggregateOperators): _$kysely.AggregateFunctionBuilder; /** * Strips alias from the node if it exists. */ declare function stripAlias(node: OperationNode): { alias: OperationNode; node: OperationNode; } | { alias: undefined; node: OperationNode; }; /** * Extracts model name from an OperationNode. */ declare function extractModelName(node: OperationNode): string | undefined; /** * Extracts field name from an OperationNode. */ declare function extractFieldName(node: OperationNode): string | undefined; declare const TEMP_ALIAS_PREFIX = "$$_"; /** * Create an alias name for a temporary table or column name. */ declare function tmpAlias(name: string): string; declare namespace schema_utils_d_exports { export { ExpressionVisitor, MatchingExpressionVisitor, VisitResult }; } type VisitResult = void | { abort: true; }; declare class ExpressionVisitor { visit(expr: Expression$1): VisitResult; protected visitLiteral(_e: LiteralExpression): VisitResult; protected visitArray(e: ArrayExpression): VisitResult; protected visitField(_e: FieldExpression): VisitResult; protected visitMember(e: MemberExpression): VisitResult; protected visitBinary(e: BinaryExpression): VisitResult; protected visitUnary(e: UnaryExpression): VisitResult; protected visitCall(e: CallExpression): VisitResult; protected visitBinding(_e: BindingExpression): VisitResult; protected visitThis(_e: ThisExpression): VisitResult; protected visitNull(_e: NullExpression): VisitResult; } declare class MatchingExpressionVisitor extends ExpressionVisitor { private predicate; private found; constructor(predicate: (expr: Expression$1) => boolean); find(expr: Expression$1): boolean; visit(expr: Expression$1): void | { readonly abort: true; }; } //#endregion export { AfterEntityMutationCallback, AggregateArgs, AggregateResult, AllCrudOperations, AllModelOperations, AllReadOperations, AllWriteOperations, AnyNull, AnyNullClass, AnyPlugin, AuthType, BaseCrudDialect, BatchResult, BeforeEntityMutationCallback, BooleanFilter, BytesFilter, CRUD, CRUD_EXT, CheckedCreateInput, CheckedUpdateInput, ClientConstructor, ClientContract, ClientOptions, ComputedFieldsOptions, CoreCreateOperations, CoreCrudOperations, CoreDeleteOperations, CoreReadOperations, CoreUpdateOperations, CoreWriteOperations, CountArgs, CountResult, CreateArgs, CreateInput, CreateManyAndReturnArgs, CreateManyArgs, CreateManyInput, CrudArgsMap, CrudArgsType, CrudReturnMap, CrudReturnType, DateTimeFilter, DbNull, DbNullClass, DefaultModelResult, DeleteArgs, DeleteManyArgs, EntityMutationHooksDef, ExistsArgs, ExtClientMembersBase, ExtQueryArgsBase, ExtQueryArgsMarker, ExtResultBase, ExtResultInferenceArgs, ExtResultMarker, ExtResultSelectOmitFields, ExtractExtResult, FilterKind, FindArgs, FindFirstArgs, FindManyArgs, FindUniqueArgs, FtsRelevanceOrderBy, FullTextFilterPayload, FuzzyFilterPayload, FuzzyRelevanceOrderBy, GetAllIncludedOperations, GetIncludedOperations, GetProcedure, GetProcedureNames, GetProcedureParams, GetQueryOptions, GetSlicedFilterKindsForField, GetSlicedModels, GetSlicedOperations, GetSlicedProcedures, GroupByArgs, GroupByResult, HasComputedFields, HasProcedures, IncludeInput, InputValidator, JsonArray, JsonFilter, JsonNull, JsonNullClass, JsonNullValues, JsonObject, JsonValue, kysely_utils_d_exports as KyselyUtils, MapModelFieldType, ModelAllowsCreate, ModelHasRequiredUnsupportedField, ModelOperations, ModelResult, ModelSlicingOptions, NullsOrder, NumberFilter, ORMError, ORMErrorReason, OmitConfig, OmitInput, OnKyselyQueryArgs, OnKyselyQueryCallback, OnProcedureHookContext, OperationsRequiringCreate, OrderBy, PluginAfterEntityMutationArgs, PluginBeforeEntityMutationArgs, ProcedureEnvelope, ProcedureFunc, ProcedureHandlerFunc, ProcedureOperations, ProceduresOptions, ProceedKyselyQueryFunction, QueryOptions, QueryRelevantOptions, query_utils_d_exports as QueryUtils, RejectedByPolicyReason, RuntimePlugin, schema_utils_d_exports as SchemaUtils, SelectAwareExtResult, SelectIncludeOmit, SelectInput, SelectSubset, SimplifiedPlainResult, SimplifiedResult, SlicingOptions, SortOrder, StringFilter, Subset, type ToKysely, TransactionClientContract, TransactionIsolationLevel, TypeDefResult, TypedJsonFilter, UncheckedCreateInput, UncheckedUpdateInput, UpdateArgs, UpdateInput, UpdateManyAndReturnArgs, UpdateManyArgs, UpsertArgs, WhereInput, WhereUniqueInput, ZModelFunction, ZModelFunctionContext, ZenStackClient, type ZenStackPromise, type ZodSchemaFactory, createQuerySchemaFactory, definePlugin, getCrudDialect }; //# sourceMappingURL=index.d.cts.map