@mongorm/orm 0.1.1-beta.1 → 0.1.1-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +414 -0
- package/dist/index.mjs +676 -0
- package/package.json +5 -1
- package/.env.example +0 -2
- package/bumpp.config.ts +0 -7
- package/src/api.ts +0 -47
- package/src/connection/database.ts +0 -145
- package/src/index.ts +0 -50
- package/src/model/model.ts +0 -212
- package/src/model/soft-delete.ts +0 -15
- package/src/query/cursor.ts +0 -36
- package/src/query/many-query.ts +0 -338
- package/src/query/query.ts +0 -14
- package/src/query/runtime.ts +0 -140
- package/src/query/types.ts +0 -134
- package/src/relations/definitions.ts +0 -136
- package/src/relations/registry.ts +0 -144
- package/src/schema/contracts.ts +0 -7
- package/src/schema/index.ts +0 -22
- package/src/schema/inference.ts +0 -17
- package/src/schema/scalars.ts +0 -110
- package/src/schema/schema.ts +0 -234
- package/src/validation/errors.ts +0 -39
- package/tests/connection/database.test.ts +0 -28
- package/tests/env.ts +0 -14
- package/tests/model/bulk.test.ts +0 -40
- package/tests/model/crud.integration.test.ts +0 -160
- package/tests/model/lifecycle.integration.test.ts +0 -44
- package/tests/query/runtime.test.ts +0 -59
- package/tests/relations/definitions.test.ts +0 -36
- package/tests/schema/core.test.ts +0 -45
- package/tests/schema/inference.test-d.ts +0 -232
- package/tests/schema/options.test.ts +0 -55
- package/tsconfig.json +0 -13
- package/tsdown.config.ts +0 -8
- package/vitest.config.ts +0 -8
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { Collection, Condition, Db as Db$1, DeleteResult, Document, FindCursor, IndexDescription, IndexDirection, MongoClientOptions, ObjectId, ObjectId as ObjectId$1, RootFilterOperators, WithId } from "mongodb";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
//#region src/schema/inference.d.ts
|
|
4
|
+
/** The raw parsed shape produced by a schema before persistence fields are added. */
|
|
5
|
+
type InferShape<T> = T extends {
|
|
6
|
+
definition: infer Definition extends z.ZodType;
|
|
7
|
+
} ? z.infer<Definition> : never;
|
|
8
|
+
/** The input type accepted by a schema before Zod defaults are applied. */
|
|
9
|
+
type InferInput<T> = T extends {
|
|
10
|
+
definition: infer Definition extends z.ZodType;
|
|
11
|
+
} ? z.input<Definition> : never;
|
|
12
|
+
/** The persisted document type inferred from a schema. */
|
|
13
|
+
type Infer<T> = InferShape<T> & {
|
|
14
|
+
_id: ObjectId$1;
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/schema/contracts.d.ts
|
|
18
|
+
/** A Zod object shape used as the source of truth for a model. */
|
|
19
|
+
type SchemaShape = z.ZodRawShape;
|
|
20
|
+
/** The runtime Zod object generated from a schema shape. */
|
|
21
|
+
type SchemaDefinition<Shape extends SchemaShape> = z.ZodObject<Shape>;
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region src/model/model.d.ts
|
|
24
|
+
type CreateInput<Shape extends SchemaShape, Options extends SchemaOptions> = Omit<InferInput<Schema<Shape, {}, {}, Options>>, '_id'>;
|
|
25
|
+
type UpdateInput<Shape extends SchemaShape, Options extends SchemaOptions> = Partial<Omit<InferInput<Schema<Shape, {}, {}, Options>>, '_id'>>;
|
|
26
|
+
type ModelDocument$1<Shape extends SchemaShape, Relations extends SchemaRelationMap, Scopes extends ScopeDefinitions, Options extends SchemaOptions> = Infer<Schema<Shape, Relations, Scopes, Options>>;
|
|
27
|
+
/** A MongoDB collection with CRUD operations derived from a schema. */
|
|
28
|
+
export declare class Model<Shape extends SchemaShape, Relations extends SchemaRelationMap = {}, Scopes extends ScopeDefinitions = {}, Options extends SchemaOptions = {}> {
|
|
29
|
+
private readonly db;
|
|
30
|
+
readonly name: string;
|
|
31
|
+
private readonly schema;
|
|
32
|
+
readonly bulk: {
|
|
33
|
+
create: (inputs: readonly CreateInput<Shape, Options>[]) => Promise<ModelDocument$1<Shape, Relations, Scopes, Options>[]>;
|
|
34
|
+
};
|
|
35
|
+
readonly restore: SoftDeleteEnabled<Options> extends true ? (filter: ModelFilter<Shape>) => Promise<Infer<Schema<Shape, Relations, Scopes, Options>> | null> : never;
|
|
36
|
+
readonly purge: SoftDeleteEnabled<Options> extends true ? (filter: ModelFilter<Shape>) => Promise<DeleteResult> : never;
|
|
37
|
+
/** Create a model bound to a database collection and schema. */
|
|
38
|
+
constructor(db: Db, name: string, schema: Schema<Shape, Relations, Scopes, Options>);
|
|
39
|
+
private get collection();
|
|
40
|
+
private activeFilter;
|
|
41
|
+
/** Validate and insert one document, generating its ObjectId. */
|
|
42
|
+
create(input: CreateInput<Shape, Options>): Promise<ModelDocument$1<Shape, Relations, Scopes, Options>>;
|
|
43
|
+
private prepareDocument;
|
|
44
|
+
private bulkCreate;
|
|
45
|
+
/** Build a query for all documents matching a MongoDB filter. */
|
|
46
|
+
find(filter?: ModelFilter<Shape>): ModelQuery<Shape, VisibleDocument<Shape>, true, Relations, Scopes, 'none', SoftDeleteEnabled<Options>>;
|
|
47
|
+
/** Validate and apply a partial update to the first matching document. */
|
|
48
|
+
update(filter: ModelFilter<Shape>, patch: UpdateInput<Shape, Options>): Promise<Infer<Schema<Shape, Relations, Scopes, Options>> | null>;
|
|
49
|
+
/** Restore matching soft-deleted documents. */
|
|
50
|
+
private restoreDocument;
|
|
51
|
+
/** Delete every document matching a MongoDB filter. */
|
|
52
|
+
delete(filter: ModelFilter<Shape>): Promise<DeleteResult>;
|
|
53
|
+
/** Permanently delete matching documents, including soft-deleted documents. */
|
|
54
|
+
private purgeDocuments;
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/connection/database.d.ts
|
|
58
|
+
type SchemaRegistry = Record<string, SchemaLike>;
|
|
59
|
+
/** Configuration for a MongoDB connection. */
|
|
60
|
+
interface DbOptions<Registry extends SchemaRegistry = SchemaRegistry> {
|
|
61
|
+
/** MongoDB connection string. */
|
|
62
|
+
uri: string;
|
|
63
|
+
/** Logical database name. */
|
|
64
|
+
database: string;
|
|
65
|
+
/** Optional native MongoDB client options. */
|
|
66
|
+
clientOptions?: MongoClientOptions;
|
|
67
|
+
/** Schemas registered as plural database model properties. */
|
|
68
|
+
schema?: Registry;
|
|
69
|
+
}
|
|
70
|
+
type ModelForSchema<SchemaType> = SchemaType extends Schema<infer Shape, infer Relations, infer Scopes, infer Options> ? Model<Shape, Relations, Scopes, Options> : never;
|
|
71
|
+
type DatabaseModels<Registry extends SchemaRegistry> = { readonly [Name in keyof Registry]: ModelForSchema<Registry[Name]>; };
|
|
72
|
+
type RegistryOfBuilder<Builder extends {
|
|
73
|
+
readonly __registry?: SchemaRegistry;
|
|
74
|
+
}> = NonNullable<Builder['__registry']>;
|
|
75
|
+
/** Owns a MongoDB client and creates schema-bound models. */
|
|
76
|
+
export declare class Db<Registry extends SchemaRegistry = SchemaRegistry> {
|
|
77
|
+
private readonly options;
|
|
78
|
+
private readonly client;
|
|
79
|
+
private database;
|
|
80
|
+
private readonly schemaCollections;
|
|
81
|
+
/** Create a disconnected database handle. */
|
|
82
|
+
constructor(options: DbOptions<Registry>);
|
|
83
|
+
/** Connect to MongoDB and select the configured database. */
|
|
84
|
+
connect(): Promise<void>;
|
|
85
|
+
/** Close the MongoDB client and release its resources. */
|
|
86
|
+
disconnect(): Promise<void>;
|
|
87
|
+
/** Create a model bound to a MongoDB collection and schema. */
|
|
88
|
+
model<Shape extends SchemaShape, Relations extends SchemaRelationMap, Scopes extends ScopeDefinitions, Options extends SchemaOptions>(name: string, schema: Schema<Shape, Relations, Scopes, Options>): Model<Shape, Relations, Scopes, Options>;
|
|
89
|
+
private registerSchema;
|
|
90
|
+
/** Resolve a registered schema to its MongoDB collection. */
|
|
91
|
+
collectionFor(schema: SchemaLike): Collection<Document>;
|
|
92
|
+
/** Explicitly create all indexes declared by registered schemas. */
|
|
93
|
+
sync(): Promise<Record<string, string[]>>;
|
|
94
|
+
/** Return the selected database, failing if `connect()` was not called. */
|
|
95
|
+
get native(): Db$1;
|
|
96
|
+
}
|
|
97
|
+
/** Create a disconnected MongoDB database handle. */
|
|
98
|
+
export declare function createDatabase<const Registry extends SchemaRegistry>(options: DbOptions<Registry> & {
|
|
99
|
+
schema: Registry;
|
|
100
|
+
}): Db<Registry> & DatabaseModels<Registry>;
|
|
101
|
+
export declare function createDatabase<const Builder extends {
|
|
102
|
+
readonly __registry?: SchemaRegistry;
|
|
103
|
+
}>(options: Omit<DbOptions<RegistryOfBuilder<Builder>>, 'schema'> & {
|
|
104
|
+
schema: Builder;
|
|
105
|
+
}): Db<RegistryOfBuilder<Builder>> & DatabaseModels<RegistryOfBuilder<Builder>>;
|
|
106
|
+
export declare function createDatabase(options: DbOptions): Db;
|
|
107
|
+
//#endregion
|
|
108
|
+
//#region src/query/cursor.d.ts
|
|
109
|
+
/** A lazy async iterable for one cursor-pagination page. */
|
|
110
|
+
export declare class ModelCursor<Shape extends SchemaShape, Result extends object> implements AsyncIterable<Result> {
|
|
111
|
+
private readonly open;
|
|
112
|
+
private readonly pageSize;
|
|
113
|
+
private readonly transform?;
|
|
114
|
+
next: ObjectId$1 | null;
|
|
115
|
+
constructor(open: () => FindCursor<WithId<StoredDocument<Shape>>>, pageSize: number, transform?: ((documents: Result[]) => Promise<Result[]>) | undefined);
|
|
116
|
+
[Symbol.asyncIterator](): AsyncGenerator<Result>;
|
|
117
|
+
}
|
|
118
|
+
//#endregion
|
|
119
|
+
//#region src/query/types.d.ts
|
|
120
|
+
type StoredDocument<Shape extends SchemaShape> = Infer<Schema<Shape>> & Document;
|
|
121
|
+
type ModelFilterForDocument<DocumentShape extends Document, FieldShape extends object = DocumentShape> = Partial<{ [Key in keyof FieldShape]: Condition<FieldShape[Key]>; }> & Partial<Pick<RootFilterOperators<DocumentShape>, '$comment' | '$expr' | '$jsonSchema' | '$text' | '$where'>> & {
|
|
122
|
+
$and?: ModelFilterForDocument<DocumentShape, FieldShape>[];
|
|
123
|
+
$nor?: ModelFilterForDocument<DocumentShape, FieldShape>[];
|
|
124
|
+
$or?: ModelFilterForDocument<DocumentShape, FieldShape>[];
|
|
125
|
+
};
|
|
126
|
+
type ModelFilter<Shape extends SchemaShape> = ModelFilterForDocument<StoredDocument<Shape>, Infer<Schema<Shape>>>;
|
|
127
|
+
type SortDirection = 'asc' | 'desc';
|
|
128
|
+
type ModelSort<Shape extends SchemaShape> = Partial<Record<Extract<keyof Infer<Schema<Shape>>, string>, SortDirection>>;
|
|
129
|
+
type ModelDocument<Shape extends SchemaShape> = Infer<Schema<Shape>>;
|
|
130
|
+
type HiddenKey<Shape extends SchemaShape> = { [Key in keyof Shape]: Shape[Key] extends {
|
|
131
|
+
readonly __hidden: true;
|
|
132
|
+
} ? Key : never; }[keyof Shape];
|
|
133
|
+
type HiddenDocumentKey<Shape extends SchemaShape> = Extract<HiddenKey<Shape>, keyof ModelDocument<Shape>> & string;
|
|
134
|
+
type NestedDocumentKeys<Value, Prefix extends string = ''> = Value extends object ? Value extends ObjectId$1 | Date ? never : { [Key in Extract<keyof Value, string>]: NonNullable<Value[Key]> extends object ? `${Prefix}${Key}` | `${Prefix}${Key}.${NestedDocumentKeys<NonNullable<Value[Key]>>}` : `${Prefix}${Key}`; }[Extract<keyof Value, string>] : never;
|
|
135
|
+
type NestedSelectableKey<Shape extends SchemaShape> = { [Key in Extract<keyof Shape, string>]: Key extends keyof ModelDocument<Shape> ? NonNullable<ModelDocument<Shape>[Key]> extends object ? `${Key}.${NestedDocumentKeys<NonNullable<ModelDocument<Shape>[Key]>>}` : never : never; }[Extract<keyof Shape, string>];
|
|
136
|
+
type CursorMethod<Shape extends SchemaShape, Result extends object, Ready extends boolean> = Ready extends true ? (after?: ObjectId$1) => ModelCursor<Shape, Result> : undefined;
|
|
137
|
+
type SelectableKey<Shape extends SchemaShape> = Exclude<Extract<keyof ModelDocument<Shape>, string>, '_id' | HiddenDocumentKey<Shape>> | NestedSelectableKey<Shape>;
|
|
138
|
+
type PathSelection<Value, Path extends string> = Path extends `${infer Head}.${infer Tail}` ? Head extends keyof Value ? { [Key in Head]: PathSelection<NonNullable<Value[Key]>, Tail>; } : never : Path extends keyof Value ? Pick<Value, Path> : never;
|
|
139
|
+
type UnionToIntersection<Value> = (Value extends unknown ? (input: Value) => void : never) extends ((input: infer Intersection) => void) ? Intersection : never;
|
|
140
|
+
type Simplify<Value> = { [Key in keyof Value]: Value[Key]; };
|
|
141
|
+
type VisibleDocument<Shape extends SchemaShape> = Omit<ModelDocument<Shape>, Extract<HiddenKey<Shape>, keyof ModelDocument<Shape>>>;
|
|
142
|
+
type SelectedDocument<Shape extends SchemaShape, Key extends SelectableKey<Shape>> = [Key] extends [never] ? VisibleDocument<Shape> : Simplify<Pick<ModelDocument<Shape>, '_id'> & UnionToIntersection<PathSelection<ModelDocument<Shape>, Extract<Key, string>>>>;
|
|
143
|
+
type RelationTarget<Relation> = Relation extends {
|
|
144
|
+
resolve: () => infer Target;
|
|
145
|
+
} ? Target : never;
|
|
146
|
+
type RelationDocument<Relation> = RelationTarget<Relation> extends Schema<infer TargetShape, any> ? Infer<Schema<TargetShape>> : never;
|
|
147
|
+
type RelationMapOf$1<Relation> = RelationTarget<Relation> extends {
|
|
148
|
+
readonly relationMap: infer TargetRelations;
|
|
149
|
+
} ? TargetRelations extends SchemaRelationMap ? TargetRelations : {} : {};
|
|
150
|
+
type ScopeName<Scopes> = Extract<keyof Scopes, string>;
|
|
151
|
+
type PopulationMode = 'none' | 'populate' | 'scope';
|
|
152
|
+
type RelationSelect<Relation> = RelationTarget<Relation> extends Schema<infer TargetShape, any> ? Exclude<SelectableKey<TargetShape>, '_id'> : never;
|
|
153
|
+
type PopulateSpec<Relations extends SchemaRelationMap> = { [Name in Extract<keyof Relations, string>]: {
|
|
154
|
+
ref: Name;
|
|
155
|
+
select?: readonly RelationSelect<Relations[Name]>[];
|
|
156
|
+
populate?: PopulateSpecs<RelationMapOf$1<Relations[Name]>>;
|
|
157
|
+
}; }[Extract<keyof Relations, string>];
|
|
158
|
+
type PopulateSpecs<Relations extends SchemaRelationMap> = readonly PopulateSpec<Relations>[];
|
|
159
|
+
type PopulatedResult<Result extends object, Relations extends SchemaRelationMap, Specs extends PopulateSpecs<Relations>> = Omit<Result, Extract<Specs[number]['ref'], keyof Result>> & { [Spec in Specs[number] as Spec['ref']]: PopulatedRelation<Relations[Spec['ref']], Spec> | null; };
|
|
160
|
+
type PopulatedRelation<Relation, Spec> = Spec extends {
|
|
161
|
+
populate: infer Nested extends PopulateSpecs<RelationMapOf$1<Relation>>;
|
|
162
|
+
} ? RelationDocument<Relation> extends (infer PopulatedDocument extends object) ? PopulatedResult<PopulatedDocument, RelationMapOf$1<Relation>, Nested> : never : RelationDocument<Relation>;
|
|
163
|
+
//#endregion
|
|
164
|
+
//#region src/query/many-query.d.ts
|
|
165
|
+
/** A typed, awaitable MongoDB find query. */
|
|
166
|
+
export declare class ModelQuery<Shape extends SchemaShape, Result extends object = VisibleDocument<Shape>, CursorReady extends boolean = true, Relations extends SchemaRelationMap = {}, Scopes extends ScopeDefinitions = {}, Mode extends PopulationMode = 'none', SoftDelete extends boolean = false> implements PromiseLike<Result[]> {
|
|
167
|
+
private readonly collection;
|
|
168
|
+
private readonly filterSpec;
|
|
169
|
+
private readonly fields;
|
|
170
|
+
private readonly hiddenFields;
|
|
171
|
+
private readonly db;
|
|
172
|
+
private readonly relations;
|
|
173
|
+
private readonly scopes;
|
|
174
|
+
private readonly softdeleteEnabled;
|
|
175
|
+
readonly deleted: SoftDelete extends true ? (mode: 'only' | 'include') => this : never;
|
|
176
|
+
private sortSpec;
|
|
177
|
+
private skipCount;
|
|
178
|
+
private limitCount;
|
|
179
|
+
private selectedFields;
|
|
180
|
+
private shownFields;
|
|
181
|
+
private populateSpecs;
|
|
182
|
+
private populationMode;
|
|
183
|
+
private readonly softDelete;
|
|
184
|
+
private readonly population;
|
|
185
|
+
readonly cursor: CursorMethod<Shape, Result, CursorReady>;
|
|
186
|
+
constructor(collection: Collection<StoredDocument<Shape>>, filterSpec: ModelFilter<Shape>, fields: readonly string[], hiddenFields: readonly string[], db: Db, relations: Relations, scopes: Scopes, softdeleteEnabled: boolean);
|
|
187
|
+
/** Include both active and soft-deleted documents in this query. */
|
|
188
|
+
private deletedMode;
|
|
189
|
+
private effectiveFilter;
|
|
190
|
+
/** Sort results by one or more schema fields. */
|
|
191
|
+
sort(spec: ModelSort<Shape>): ModelQuery<Shape, Result, false, Relations, Scopes, Mode, SoftDelete>;
|
|
192
|
+
/** Skip a non-negative number of matching documents. */
|
|
193
|
+
skip(count: number): ModelQuery<Shape, Result, false, Relations, Scopes, Mode, SoftDelete>;
|
|
194
|
+
/** Limit the number of matching documents returned. */
|
|
195
|
+
limit(count: number): this;
|
|
196
|
+
/** Return only selected fields, while retaining MongoDB's default `_id`. */
|
|
197
|
+
select<Keys extends SelectableKey<Shape> = never>(fields?: readonly Keys[]): ModelQuery<Shape, SelectedDocument<Shape, Keys>, CursorReady, Relations, Scopes, Mode, SoftDelete>;
|
|
198
|
+
/** Include hidden fields in the query result. */
|
|
199
|
+
show<Keys extends HiddenDocumentKey<Shape>>(fields: readonly Keys[]): ModelQuery<Shape, Result & Pick<ModelDocument<Shape>, Keys>, CursorReady, Relations, Scopes, Mode, SoftDelete>;
|
|
200
|
+
/** Populate declared one-way relations, including nested relation arrays. */
|
|
201
|
+
populate<Specs extends PopulateSpecs<Relations>>(this: Mode extends 'scope' ? never : ModelQuery<Shape, Result, CursorReady, Relations, Scopes, Mode, SoftDelete>, specs: Specs): ModelQuery<Shape, PopulatedResult<Result, Relations, Specs>, CursorReady, Relations, Scopes, 'populate', SoftDelete>;
|
|
202
|
+
/** Apply a named population scope. */
|
|
203
|
+
with<Name extends ScopeName<Scopes>>(this: Mode extends 'populate' ? never : ModelQuery<Shape, Result, CursorReady, Relations, Scopes, Mode, SoftDelete>, name: Name): ModelQuery<Shape, PopulatedResult<Result, Relations, Scopes[Name] & PopulateSpecs<Relations>>, CursorReady, Relations, Scopes, 'scope', SoftDelete>;
|
|
204
|
+
/** Count matching documents, optionally using MongoDB's collection estimate. */
|
|
205
|
+
count(estimate?: boolean): Promise<number>;
|
|
206
|
+
/** Return one `_id`-ordered page and the cursor for the next page. */
|
|
207
|
+
private createCursor;
|
|
208
|
+
private execute;
|
|
209
|
+
first(): Promise<Result | null>;
|
|
210
|
+
private createQueryCursor;
|
|
211
|
+
then<TResult1 = Result[], TResult2 = never>(onfulfilled?: ((value: Result[]) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): PromiseLike<TResult1 | TResult2>;
|
|
212
|
+
}
|
|
213
|
+
//#endregion
|
|
214
|
+
//#region src/schema/schema.d.ts
|
|
215
|
+
/** Built-in persistence behavior applied by a schema. */
|
|
216
|
+
interface SchemaOptions {
|
|
217
|
+
readonly timestamps?: boolean;
|
|
218
|
+
readonly softdelete?: boolean;
|
|
219
|
+
}
|
|
220
|
+
type SchemaIndexFields<Shape extends SchemaShape> = Partial<Record<Extract<keyof Shape, string>, IndexDirection>>;
|
|
221
|
+
type SchemaIndex<Shape extends SchemaShape> = {
|
|
222
|
+
readonly fields: SchemaIndexFields<Shape>;
|
|
223
|
+
readonly options?: Omit<IndexDescription, 'key'>;
|
|
224
|
+
};
|
|
225
|
+
type TimestampShape = {
|
|
226
|
+
createdAt: z.ZodDefault<z.ZodDate>;
|
|
227
|
+
updatedAt: z.ZodDefault<z.ZodDate>;
|
|
228
|
+
};
|
|
229
|
+
type SoftDeleteShape = {
|
|
230
|
+
deletedAt: z.ZodDefault<z.ZodNullable<z.ZodDate>>;
|
|
231
|
+
};
|
|
232
|
+
type ManagedShape<Options extends SchemaOptions> = (Options['timestamps'] extends true ? TimestampShape : {}) & (Options['softdelete'] extends true ? SoftDeleteShape : {});
|
|
233
|
+
type ManagedField<Options extends SchemaOptions> = (Options['timestamps'] extends true ? 'createdAt' | 'updatedAt' : never) | (Options['softdelete'] extends true ? 'deletedAt' : never);
|
|
234
|
+
type SoftDeleteEnabled<Options extends SchemaOptions> = Options['softdelete'] extends true ? true : false;
|
|
235
|
+
export declare const hasSoftDelete: (options: SchemaOptions) => boolean;
|
|
236
|
+
type ObjectIdFieldKeys<Shape extends SchemaShape> = { [Key in keyof InferShape<Schema<Shape>>]-?: NonNullable<InferShape<Schema<Shape>>[Key]> extends ObjectId$1 ? Key : never; }[keyof InferShape<Schema<Shape>>];
|
|
237
|
+
type ScopeDefinitions = Record<string, readonly object[]>;
|
|
238
|
+
/** A typed, runtime-validated schema definition. */
|
|
239
|
+
export declare class Schema<Shape extends SchemaShape, Relations extends SchemaRelationMap = {}, Scopes extends ScopeDefinitions = {}, Options extends SchemaOptions = {}> {
|
|
240
|
+
/** The underlying Zod object for advanced validation use cases. */
|
|
241
|
+
readonly definition: SchemaDefinition<Shape>;
|
|
242
|
+
/** The lazily resolved relation metadata declared by this schema. */
|
|
243
|
+
readonly refs: RelationMap<Shape>;
|
|
244
|
+
/** One-way relation metadata declared for this schema. */
|
|
245
|
+
readonly relationMap: Relations;
|
|
246
|
+
/** Named population scopes declared for this schema. */
|
|
247
|
+
scopeMap: Scopes;
|
|
248
|
+
/** Field names excluded from default query results. */
|
|
249
|
+
readonly hiddenFields: readonly (keyof Shape & string)[];
|
|
250
|
+
/** Field names declared by this schema. */
|
|
251
|
+
readonly fields: readonly (keyof Shape & string)[];
|
|
252
|
+
/** Persistence behavior enabled for this schema. */
|
|
253
|
+
readonly optionsConfig: Options;
|
|
254
|
+
/** MongoDB indexes declared for this schema. */
|
|
255
|
+
indexDefinitions: readonly SchemaIndex<Shape>[];
|
|
256
|
+
/** Preserve schema options through registry type transformations. */
|
|
257
|
+
readonly __options: Options;
|
|
258
|
+
/** Construct a schema from a Zod object shape. */
|
|
259
|
+
constructor(shape: Shape, relations?: Relations, scopeMap?: Scopes, optionsConfig?: Options, indexDefinitions?: readonly SchemaIndex<Shape>[]);
|
|
260
|
+
/** Enable managed timestamps and/or soft deletion for this schema. */
|
|
261
|
+
options<const Enabled extends SchemaOptions>(options: Enabled): Schema<Shape & ManagedShape<Enabled>, Relations, Scopes, Enabled>;
|
|
262
|
+
/** Declare MongoDB indexes for explicit synchronization with the database. */
|
|
263
|
+
indexes<const Definitions extends readonly SchemaIndex<Shape>[]>(definitions: Definitions): this;
|
|
264
|
+
/** Add one or more one-way relations without requiring circular schema declarations. */
|
|
265
|
+
relations<const Definitions extends Partial<Record<Extract<ObjectIdFieldKeys<Shape>, string>, RelationInput>>>(definitions: Definitions & Record<Exclude<keyof Definitions, Extract<ObjectIdFieldKeys<Shape>, string>>, never>): Schema<Shape, Relations & { [Name in keyof Definitions]: SchemaRelation<RelationInputTarget<NonNullable<Definitions[Name]>>, Extract<Name, string>, NonNullable<Definitions[Name]> extends {
|
|
266
|
+
foreignField: infer Foreign extends string;
|
|
267
|
+
} ? Foreign : '_id'>; }, Scopes, Options>;
|
|
268
|
+
/** Declare named, reusable population scopes. */
|
|
269
|
+
scopes<const Definitions extends Record<string, PopulateSpecs<Relations>>>(definitions: Definitions): Schema<Shape, Relations, Definitions, Options>;
|
|
270
|
+
/** Parse unknown input and return the inferred document type. */
|
|
271
|
+
parse(input: unknown): InferShape<this>;
|
|
272
|
+
/** Parse a partial document for update operations. */
|
|
273
|
+
parsePartial(input: unknown): Partial<InferShape<this>>;
|
|
274
|
+
/** Parse unknown input without throwing on validation failure. */
|
|
275
|
+
safeParse(input: unknown): ReturnType<typeof this.definition.safeParse>;
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
//#region src/relations/definitions.d.ts
|
|
279
|
+
/** A schema-like target resolved lazily to support circular module imports. */
|
|
280
|
+
type SchemaLike = Schema<SchemaShape, any, any, any>;
|
|
281
|
+
/** Metadata attached to a forward relation field. */
|
|
282
|
+
interface RefDefinition<Target extends SchemaLike = SchemaLike> {
|
|
283
|
+
/** Resolve the related schema after module initialization completes. */
|
|
284
|
+
resolve: () => Target;
|
|
285
|
+
}
|
|
286
|
+
/** Metadata for a one-way relation between two MongoDB schemas. */
|
|
287
|
+
interface SchemaRelation<Target extends SchemaLike = SchemaLike, LocalField extends string = string, ForeignField extends string = string> {
|
|
288
|
+
readonly resolve: () => Target;
|
|
289
|
+
readonly localField: LocalField;
|
|
290
|
+
readonly foreignField: ForeignField;
|
|
291
|
+
}
|
|
292
|
+
/** Relation metadata attached to a schema. */
|
|
293
|
+
type SchemaRelationMap = Record<string, SchemaRelation>;
|
|
294
|
+
/** A relation target declaration accepted by Schema.relations(). */
|
|
295
|
+
type RelationInput<Target extends SchemaLike = SchemaLike> = (() => Target) | {
|
|
296
|
+
target: () => Target;
|
|
297
|
+
foreignField?: string;
|
|
298
|
+
};
|
|
299
|
+
/** Extract a relation target from a relation declaration. */
|
|
300
|
+
type RelationInputTarget<Input> = Input extends (() => infer Target) ? Target : Input extends {
|
|
301
|
+
target: () => infer Target;
|
|
302
|
+
} ? Target : never;
|
|
303
|
+
/** A string identifier field carrying a typed relation target. */
|
|
304
|
+
type RefField<Target extends SchemaLike = SchemaLike> = z.ZodType<ObjectId$1> & {
|
|
305
|
+
readonly __ref?: RefDefinition<Target>;
|
|
306
|
+
optional(): OptionalRefField<Target>;
|
|
307
|
+
nullable(): NullableRefField<Target>;
|
|
308
|
+
nullish(): NullishRefField<Target>;
|
|
309
|
+
};
|
|
310
|
+
/** An optional relation field that retains its target metadata. */
|
|
311
|
+
type OptionalRefField<Target extends SchemaLike = SchemaLike> = z.ZodOptional<RefField<Target>> & {
|
|
312
|
+
readonly __ref?: RefDefinition<Target>;
|
|
313
|
+
};
|
|
314
|
+
/** A nullable relation field that retains its target metadata. */
|
|
315
|
+
type NullableRefField<Target extends SchemaLike = SchemaLike> = z.ZodNullable<RefField<Target>> & {
|
|
316
|
+
readonly __ref?: RefDefinition<Target>;
|
|
317
|
+
};
|
|
318
|
+
/** An optional and nullable relation field that retains its target metadata. */
|
|
319
|
+
type NullishRefField<Target extends SchemaLike = SchemaLike> = z.ZodOptional<NullableRefField<Target>> & {
|
|
320
|
+
readonly __ref?: RefDefinition<Target>;
|
|
321
|
+
};
|
|
322
|
+
type RelationDefinition<Field> = Field extends {
|
|
323
|
+
readonly __ref?: infer Definition;
|
|
324
|
+
} ? NonNullable<Definition> : Field extends z.ZodOptional<infer Inner> ? RelationDefinition<Inner> : Field extends z.ZodNullable<infer Inner> ? RelationDefinition<Inner> : never;
|
|
325
|
+
/** The relation metadata inferred from a schema shape. */
|
|
326
|
+
type RelationMap<Shape extends SchemaShape> = { [Key in keyof Shape as RelationDefinition<Shape[Key]> extends never ? never : Key]: RelationDefinition<Shape[Key]>; };
|
|
327
|
+
//#endregion
|
|
328
|
+
//#region src/relations/registry.d.ts
|
|
329
|
+
type ObjectIdKeys<Shape extends SchemaShape> = { [Key in keyof InferShape<Schema<Shape>>]-?: NonNullable<InferShape<Schema<Shape>>[Key]> extends ObjectId$1 ? Key : never; }[keyof InferShape<Schema<Shape>>];
|
|
330
|
+
type RelationDefinitions<Registry extends Record<string, SchemaLike>> = { [Name in keyof Registry]?: Registry[Name] extends Schema<infer Shape, any, any, any> ? Partial<Record<Extract<ObjectIdKeys<Shape>, string>, Extract<keyof Registry, string>>> : never; };
|
|
331
|
+
type EnrichedSchema<Registry extends Record<string, SchemaLike>, AllDefinitions extends RelationDefinitions<Registry>, Name> = Name extends keyof Registry ? Registry[Name] extends Schema<infer Shape, infer Relations, infer Scopes, infer Options> ? Schema<Shape, Relations & RelationsFor<Registry, AllDefinitions, NonNullable<AllDefinitions[Name]>>, Scopes, Options> : never : never;
|
|
332
|
+
type RelationsFor<Registry extends Record<string, SchemaLike>, AllDefinitions extends RelationDefinitions<Registry>, Definitions> = { [Field in keyof Definitions & string]: Definitions[Field] extends keyof Registry ? SchemaRelation<EnrichedSchema<Registry, AllDefinitions, Definitions[Field]>, Field, '_id'> : never; };
|
|
333
|
+
type RegistryWithRelations<Registry extends Record<string, SchemaLike>, Definitions extends RelationDefinitions<Registry>> = { [Name in keyof Registry]: Registry[Name] extends Schema<infer Shape, infer Relations, infer Scopes, infer Options> ? Schema<Shape, Relations & RelationsFor<Registry, Definitions, NonNullable<Definitions[Name]>>, Scopes, Options> : Registry[Name]; };
|
|
334
|
+
type RelationMapOf<Value> = Value extends Schema<any, infer Relations, any, any> ? Relations : {};
|
|
335
|
+
type ScopeDefinitionsBySchema<Registry extends Record<string, SchemaLike>> = { [Name in keyof Registry]?: Record<string, PopulateSpecs<RelationMapOf<Registry[Name]>>>; };
|
|
336
|
+
type RegistryWithScopes<Registry extends Record<string, SchemaLike>, Definitions extends ScopeDefinitionsBySchema<Registry>> = { [Name in keyof Registry]: Registry[Name] extends Schema<infer Shape, infer Relations, infer Scopes, infer Options> ? Schema<Shape, Relations, Scopes & (Definitions[Name] extends ScopeDefinitions ? Definitions[Name] : {}), Options> : Registry[Name]; };
|
|
337
|
+
type SchemaRegistryBuilder<Registry extends Record<string, SchemaLike>> = Registry & {
|
|
338
|
+
readonly __registry?: Registry;
|
|
339
|
+
defineRelations<const Definitions extends RelationDefinitions<Registry>>(definitions: Definitions): SchemaRegistryBuilder<RegistryWithRelations<Registry, Definitions>>;
|
|
340
|
+
defineScopes<const Definitions extends ScopeDefinitionsBySchema<Registry>>(definitions: Definitions): SchemaRegistryBuilder<RegistryWithScopes<Registry, Definitions>>;
|
|
341
|
+
};
|
|
342
|
+
declare const createSchemaRegistry: <const Registry extends Record<string, SchemaLike>>(registry: Registry) => SchemaRegistryBuilder<Registry>;
|
|
343
|
+
//#endregion
|
|
344
|
+
//#region src/schema/scalars.d.ts
|
|
345
|
+
declare module 'zod' {
|
|
346
|
+
interface ZodType {
|
|
347
|
+
hidden(): this & {
|
|
348
|
+
readonly __hidden: true;
|
|
349
|
+
};
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
/** A schema field that can be marked as hidden from default query results. */
|
|
353
|
+
type HiddenCapable<T extends z.ZodType> = Omit<T, 'optional' | 'nullable' | 'nullish'> & HiddenMethods<T>;
|
|
354
|
+
/** A schema field marked as hidden from default query results. */
|
|
355
|
+
type HiddenSchema<T extends z.ZodType> = Omit<T, 'optional' | 'nullable' | 'nullish'> & HiddenMethods<T> & {
|
|
356
|
+
readonly __hidden: true;
|
|
357
|
+
};
|
|
358
|
+
type HiddenMethods<T extends z.ZodType> = {
|
|
359
|
+
hidden(): HiddenSchema<T>;
|
|
360
|
+
optional(): HiddenCapable<z.ZodOptional<T>>;
|
|
361
|
+
nullable(): HiddenCapable<z.ZodNullable<T>>;
|
|
362
|
+
nullish(): HiddenCapable<z.ZodOptional<z.ZodNullable<T>>>;
|
|
363
|
+
};
|
|
364
|
+
/** Create a MongoDB ObjectId schema. */
|
|
365
|
+
declare const objectId: () => HiddenCapable<z.ZodInstanceOf<ObjectId$1>>;
|
|
366
|
+
//#endregion
|
|
367
|
+
//#region src/api.d.ts
|
|
368
|
+
type ZodConstructorKey = { [Key in keyof typeof z]: Key extends string ? Key extends Lowercase<Key> ? (typeof z)[Key] extends ((...args: any[]) => any) ? Key : never : never : never; }[keyof typeof z];
|
|
369
|
+
type ZodConstructors = Pick<typeof z, ZodConstructorKey>;
|
|
370
|
+
/** The public schema-construction API. */
|
|
371
|
+
type OrmApi = ZodConstructors & {
|
|
372
|
+
/** Define a typed object schema. */
|
|
373
|
+
schema<Shape extends SchemaShape>(shape: Shape): Schema<Shape>;
|
|
374
|
+
/** Build a registry of named schemas and their relation graph. */
|
|
375
|
+
defineSchemas<const Registry extends Record<string, SchemaLike>>(registry: Registry): ReturnType<typeof createSchemaRegistry<Registry>>;
|
|
376
|
+
/** Create a MongoDB ObjectId field. */
|
|
377
|
+
objectId: typeof objectId;
|
|
378
|
+
/** Create a string ID field linked to another schema. */
|
|
379
|
+
ref<Target extends SchemaLike>(resolve: () => Target): RefField<Target>;
|
|
380
|
+
};
|
|
381
|
+
export declare const orm: OrmApi;
|
|
382
|
+
//#endregion
|
|
383
|
+
//#region src/validation/errors.d.ts
|
|
384
|
+
/** Stable machine-readable codes emitted by Mongorm errors. */
|
|
385
|
+
export declare const ORM_ERROR_CODES: {
|
|
386
|
+
readonly DATABASE_NOT_CONNECTED: 'DATABASE_NOT_CONNECTED';
|
|
387
|
+
readonly INVALID_QUERY: 'INVALID_QUERY';
|
|
388
|
+
readonly CURSOR_QUERY_INVALID: 'CURSOR_QUERY_INVALID';
|
|
389
|
+
readonly ESTIMATED_COUNT_FILTER_UNSUPPORTED: 'ESTIMATED_COUNT_FILTER_UNSUPPORTED';
|
|
390
|
+
};
|
|
391
|
+
type OrmErrorCode = (typeof ORM_ERROR_CODES)[keyof typeof ORM_ERROR_CODES];
|
|
392
|
+
/** Base error type emitted by the ORM. */
|
|
393
|
+
export declare class OrmError extends Error {
|
|
394
|
+
readonly code: OrmErrorCode;
|
|
395
|
+
constructor(message: string, code: OrmErrorCode);
|
|
396
|
+
}
|
|
397
|
+
/** Raised when an operation requires a connected database. */
|
|
398
|
+
export declare class DatabaseNotConnectedError extends OrmError {
|
|
399
|
+
constructor();
|
|
400
|
+
}
|
|
401
|
+
/** Raised when a query configuration is not supported. */
|
|
402
|
+
export declare class InvalidQueryError extends OrmError {
|
|
403
|
+
constructor(message: string, code?: OrmErrorCode);
|
|
404
|
+
}
|
|
405
|
+
/** Raised when cursor pagination options are incompatible. */
|
|
406
|
+
export declare class CursorQueryError extends InvalidQueryError {
|
|
407
|
+
constructor(message: string);
|
|
408
|
+
}
|
|
409
|
+
/** Raised when an estimated count is requested with a filter. */
|
|
410
|
+
export declare class EstimatedCountError extends InvalidQueryError {
|
|
411
|
+
constructor();
|
|
412
|
+
}
|
|
413
|
+
//#endregion
|
|
414
|
+
export { type DatabaseModels, type DbOptions, type HiddenDocumentKey, type Infer, type InferInput, type InferShape, type ManagedField, type ModelFilter, type ModelSort, ObjectId, type OrmApi, type OrmErrorCode, type PopulateSpec, type PopulateSpecs, type PopulatedResult, type RefDefinition, type RefField, type RelationDefinitions, type RelationMap, type SchemaDefinition, type SchemaIndex, type SchemaIndexFields, type SchemaLike, type SchemaOptions, type SchemaRegistry, type SchemaRegistryBuilder, type SchemaRelation, type SchemaRelationMap, type SchemaShape, type ScopeDefinitionsBySchema, type SelectableKey, type SelectedDocument, type SoftDeleteEnabled, type StoredDocument, type VisibleDocument };
|