modelence 0.6.18 → 0.6.20

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/server.d.ts CHANGED
@@ -1,496 +1,13 @@
1
1
  import { A as AppServer } from './index-CwdohC5n.js';
2
- import { P as Permission, S as Session, U as UserInfo, C as ConfigSchema, d as ServerChannel, e as User, W as WebsocketServerProvider, R as RoleDefinition, b as ConfigKey, A as AppConfig, f as Role } from './types-CmI2APz9.js';
3
- import * as mongodb from 'mongodb';
4
- import { ObjectId as ObjectId$1, WithId, IndexDescription, SearchIndexDescription, MongoClient, Collection, Filter, FindOptions, Document, OptionalUnlessRequiredId, InsertOneResult, InsertManyResult, UpdateFilter, UpdateResult, ClientSession, DeleteResult, AggregateOptions, AggregationCursor, AnyBulkWriteOperation, BulkWriteResult } from 'mongodb';
2
+ import { C as ConfigSchema, S as ServerChannel, U as User, d as Session, W as WebsocketServerProvider, R as RoleDefinition, b as ConfigKey, A as AppConfig, e as UserInfo, f as Role } from './types-Ds1ESQSs.js';
3
+ import { S as Store, M as MethodDefinition, R as RouteDefinition, C as CronJobInputParams, a as RateLimitRule, E as EmailProvider, b as ConnectionInfo, I as InferDocumentType, c as RateLimitType, d as EmailPayload } from './types-D6nwUab6.js';
4
+ export { H as HttpMethod, e as RouteHandler, f as RouteParams, g as RouteResponse, s as schema } from './types-D6nwUab6.js';
5
+ import { ObjectId as ObjectId$1 } from 'mongodb';
5
6
  export { ObjectId } from 'mongodb';
6
7
  import * as zod from 'zod';
7
- import { z, ZodNumber, ZodArray } from 'zod';
8
- import { Request, Response, NextFunction } from 'express';
9
- import { EmailProvider, EmailPayload } from './types.js';
8
+ import 'express';
10
9
  import 'http';
11
10
 
12
- type CronJobHandler = () => Promise<void>;
13
- type CronJobInputParams = {
14
- description?: string;
15
- interval: number;
16
- timeout?: number;
17
- handler: CronJobHandler;
18
- };
19
-
20
- type ObjectTypeDefinition = {
21
- [key: string]: SchemaTypeDefinition;
22
- };
23
- type SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition;
24
- type SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;
25
- type ModelSchema = {
26
- [key: string]: SchemaTypeDefinition;
27
- };
28
- type InferDocumentType<T extends SchemaTypeDefinition> = {
29
- [K in keyof T as T[K] extends z.ZodOptional<z.ZodTypeAny> ? K : never]?: T[K] extends z.ZodType ? z.infer<T[K]> : never;
30
- } & {
31
- [K in keyof T as T[K] extends z.ZodOptional<z.ZodTypeAny> ? never : K]: T[K] extends z.ZodType ? z.infer<T[K]> : T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> : T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> : never;
32
- };
33
- declare const schema: {
34
- readonly string: (params?: z.RawCreateParams & {
35
- coerce?: true;
36
- }) => z.ZodString;
37
- readonly number: (params?: z.RawCreateParams & {
38
- coerce?: boolean;
39
- }) => ZodNumber;
40
- readonly date: (params?: z.RawCreateParams & {
41
- coerce?: boolean;
42
- }) => z.ZodDate;
43
- readonly boolean: (params?: z.RawCreateParams & {
44
- coerce?: boolean;
45
- }) => z.ZodBoolean;
46
- readonly array: <El extends z.ZodTypeAny>(schema: El, params?: z.RawCreateParams) => ZodArray<El>;
47
- readonly object: <Shape extends z.ZodRawShape>(shape: Shape, params?: z.RawCreateParams) => z.ZodObject<Shape, "strip", z.ZodTypeAny, z.objectOutputType<Shape, z.ZodTypeAny, "strip">, z.objectInputType<Shape, z.ZodTypeAny, "strip">>;
48
- readonly enum: {
49
- <U extends string, T extends Readonly<[U, ...U[]]>>(values: T, params?: z.RawCreateParams): z.ZodEnum<z.Writeable<T>>;
50
- <U extends string, T extends [U, ...U[]]>(values: T, params?: z.RawCreateParams): z.ZodEnum<T>;
51
- };
52
- readonly embedding: () => ZodArray<ZodNumber>;
53
- readonly objectId: () => z.ZodType<ObjectId$1>;
54
- readonly userId: () => z.ZodType<ObjectId$1>;
55
- readonly ref: <T extends ModelSchema>(_collection: string | Store<T, InferDocumentType<T>>) => z.ZodType<ObjectId$1>;
56
- readonly union: <Options extends Readonly<[z.ZodTypeAny, z.ZodTypeAny, ...z.ZodTypeAny[]]>>(types: Options, params?: z.RawCreateParams) => z.ZodUnion<Options>;
57
- readonly infer: <T extends SchemaTypeDefinition>(_schema: T) => InferDocumentType<T>;
58
- };
59
- declare namespace schema {
60
- type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;
61
- }
62
-
63
- interface SerializedModelSchema {
64
- [key: string]: SerializedSchema | (SerializedSchema | SerializedModelSchema)[] | SerializedModelSchema | 'v2';
65
- }
66
- type BaseSerializedSchema = {
67
- type: 'string';
68
- } | {
69
- type: 'number';
70
- } | {
71
- type: 'boolean';
72
- } | {
73
- type: 'date';
74
- } | {
75
- type: 'array';
76
- items: SerializedSchema;
77
- } | {
78
- type: 'object';
79
- items: Record<string, SerializedSchema>;
80
- } | {
81
- type: 'enum';
82
- items: readonly string[];
83
- } | {
84
- type: 'union';
85
- items: SerializedSchema[];
86
- } | {
87
- type: 'custom';
88
- typeName: string;
89
- };
90
- type SerializedSchema = BaseSerializedSchema | (BaseSerializedSchema & {
91
- optional: true;
92
- });
93
-
94
- /**
95
- * Helper type to preserve method types when extending a store.
96
- * Maps each method to work with the extended schema while preserving signatures.
97
- * @internal
98
- */
99
- type PreserveMethodsForExtendedSchema<TBaseMethods extends Record<string, (...args: never[]) => unknown>, TExtendedSchema extends ModelSchema> = {
100
- [K in keyof TBaseMethods]: TBaseMethods[K] extends (this: any, ...args: infer Args) => infer Return ? (this: WithId<InferDocumentType<TExtendedSchema>> & any, ...args: Args) => Return : never;
101
- };
102
- /**
103
- * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.
104
- *
105
- * @category Store
106
- * @typeParam TSchema - The document schema type
107
- * @typeParam TMethods - Custom methods that will be added to documents
108
- *
109
- * @example
110
- * ```ts
111
- * const dbTodos = new Store('todos', {
112
- * schema: {
113
- * title: schema.string(),
114
- * completed: schema.boolean(),
115
- * dueDate: schema.date().optional(),
116
- * userId: schema.userId(),
117
- * },
118
- * methods: {
119
- * isOverdue() {
120
- * return this.dueDate < new Date();
121
- * }
122
- * }
123
- * });
124
- * ```
125
- */
126
- declare class Store<TSchema extends ModelSchema, TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: any[]) => any>> {
127
- /** @internal */
128
- readonly _type: InferDocumentType<TSchema>;
129
- /** @internal */
130
- readonly _rawDoc: WithId<this['_type']>;
131
- /** @internal */
132
- readonly _doc: this['_rawDoc'] & TMethods;
133
- readonly Doc: this['_doc'];
134
- private name;
135
- private readonly schema;
136
- private readonly methods?;
137
- private readonly indexes;
138
- private readonly searchIndexes;
139
- private collection?;
140
- private client?;
141
- /**
142
- * Creates a new Store instance
143
- *
144
- * @param name - The collection name in MongoDB
145
- * @param options - Store configuration
146
- */
147
- constructor(name: string, options: {
148
- /** Document schema using Modelence schema types */
149
- schema: TSchema;
150
- /** Custom methods to add to documents */
151
- methods?: TMethods;
152
- /** MongoDB indexes to create */
153
- indexes: IndexDescription[];
154
- /** MongoDB Atlas Search */
155
- searchIndexes?: SearchIndexDescription[];
156
- });
157
- getName(): string;
158
- /** @internal */
159
- getSchema(): TSchema;
160
- /** @internal */
161
- getSerializedSchema(): SerializedModelSchema;
162
- /**
163
- * Extends the store with additional schema fields, indexes, methods, and search indexes.
164
- * Returns a new Store instance with the extended schema and updated types.
165
- * Methods from the original store are preserved with updated type signatures.
166
- *
167
- * @param config - Additional schema fields, indexes, methods, and search indexes to add
168
- * @returns A new Store instance with the extended schema
169
- *
170
- * @example
171
- * ```ts
172
- * // Extend the users collection
173
- * export const dbUsers = baseUsersCollection.extend({
174
- * schema: {
175
- * firstName: schema.string(),
176
- * lastName: schema.string(),
177
- * companyId: schema.objectId().optional(),
178
- * },
179
- * indexes: [
180
- * { key: { companyId: 1 } },
181
- * { key: { lastName: 1, firstName: 1 } },
182
- * ],
183
- * methods: {
184
- * getFullName() {
185
- * return `${this.firstName} ${this.lastName}`;
186
- * }
187
- * }
188
- * });
189
- *
190
- * // Now fully typed with new fields
191
- * const user = await dbUsers.findOne({ firstName: 'John' });
192
- * console.log(user?.getFullName());
193
- * ```
194
- */
195
- extend<TExtendedSchema extends ModelSchema, TExtendedMethods extends Record<string, (this: WithId<InferDocumentType<TSchema & TExtendedSchema>> & any, ...args: any[]) => any> = Record<string, never>>(config: {
196
- schema?: TExtendedSchema;
197
- indexes?: IndexDescription[];
198
- methods?: TExtendedMethods;
199
- searchIndexes?: SearchIndexDescription[];
200
- }): Store<TSchema & TExtendedSchema, PreserveMethodsForExtendedSchema<TMethods, TSchema & TExtendedSchema> & TExtendedMethods>;
201
- /** @internal */
202
- init(client: MongoClient): void;
203
- /** @internal */
204
- createIndexes(): Promise<void>;
205
- private wrapDocument;
206
- /**
207
- * For convenience, to also allow directy passing a string or ObjectId as the selector
208
- */
209
- private getSelector;
210
- /** @internal */
211
- requireCollection(): Collection<this["_type"]>;
212
- /** @internal */
213
- requireClient(): MongoClient;
214
- findOne(query: Filter<this['_type']>, options?: FindOptions): Promise<this["_doc"] | null>;
215
- requireOne(query: Filter<this['_type']>, options?: FindOptions, errorHandler?: () => Error): Promise<this['_doc']>;
216
- private find;
217
- /**
218
- * Fetches a single document by its ID
219
- *
220
- * @param id - The ID of the document to find
221
- * @returns The document, or null if not found
222
- */
223
- findById(id: string | ObjectId$1): Promise<this['_doc'] | null>;
224
- /**
225
- * Fetches a single document by its ID, or throws an error if not found
226
- *
227
- * @param id - The ID of the document to find
228
- * @param errorHandler - Optional error handler to return a custom error if the document is not found
229
- * @returns The document
230
- */
231
- requireById(id: string | ObjectId$1, errorHandler?: () => Error): Promise<this['_doc']>;
232
- /**
233
- * Counts the number of documents that match a query
234
- *
235
- * @param query - The query to filter documents
236
- * @returns The number of documents that match the query
237
- */
238
- countDocuments(query: Filter<this['_type']>): Promise<number>;
239
- /**
240
- * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.
241
- *
242
- * @param query - The query to filter documents
243
- * @param options - Options
244
- * @returns The documents
245
- */
246
- fetch(query: Filter<this['_type']>, options?: {
247
- sort?: Document;
248
- limit?: number;
249
- skip?: number;
250
- }): Promise<this['_doc'][]>;
251
- /**
252
- * Inserts a single document
253
- *
254
- * @param document - The document to insert
255
- * @returns The result of the insert operation
256
- */
257
- insertOne(document: OptionalUnlessRequiredId<InferDocumentType<TSchema>>): Promise<InsertOneResult>;
258
- /**
259
- * Inserts multiple documents
260
- *
261
- * @param documents - The documents to insert
262
- * @returns The result of the insert operation
263
- */
264
- insertMany(documents: OptionalUnlessRequiredId<InferDocumentType<TSchema>>[]): Promise<InsertManyResult>;
265
- /**
266
- * Updates a single document
267
- *
268
- * @param selector - The selector to find the document to update
269
- * @param update - The update to apply to the document
270
- * @returns The result of the update operation
271
- */
272
- updateOne(selector: Filter<this['_type']> | string | ObjectId$1, update: UpdateFilter<this['_type']>): Promise<UpdateResult>;
273
- /**
274
- * Updates a single document, or inserts it if it doesn't exist
275
- *
276
- * @param selector - The selector to find the document to update
277
- * @param update - The MongoDB modifier to apply to the document
278
- * @returns The result of the update operation
279
- */
280
- upsertOne(selector: Filter<this['_type']> | string | ObjectId$1, update: UpdateFilter<this['_type']>): Promise<UpdateResult>;
281
- /**
282
- * Updates multiple documents
283
- *
284
- * @param selector - The selector to find the documents to update
285
- * @param update - The MongoDB modifier to apply to the documents
286
- * @returns The result of the update operation
287
- */
288
- updateMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>, options?: {
289
- session?: ClientSession;
290
- }): Promise<UpdateResult>;
291
- /**
292
- * Updates multiple documents, or inserts them if they don't exist
293
- *
294
- * @param selector - The selector to find the documents to update
295
- * @param update - The MongoDB modifier to apply to the documents
296
- * @returns The result of the update operation
297
- */
298
- upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult>;
299
- /**
300
- * Deletes a single document
301
- *
302
- * @param selector - The selector to find the document to delete
303
- * @returns The result of the delete operation
304
- */
305
- deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult>;
306
- /**
307
- * Deletes multiple documents
308
- *
309
- * @param selector - The selector to find the documents to delete
310
- * @returns The result of the delete operation
311
- */
312
- deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult>;
313
- /**
314
- * Aggregates documents using MongoDB's aggregation framework
315
- *
316
- * @param pipeline - The aggregation pipeline
317
- * @param options - Optional options
318
- * @returns The aggregation cursor
319
- */
320
- aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document>;
321
- /**
322
- * Performs a bulk write operation on the collection
323
- *
324
- * @param operations - The operations to perform
325
- * @returns The result of the bulk write operation
326
- */
327
- bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult>;
328
- /**
329
- * Returns the raw MongoDB database instance for advanced operations
330
- * @returns The MongoDB database instance
331
- * @throws Error if the store is not provisioned
332
- */
333
- getDatabase(): mongodb.Db;
334
- /**
335
- * Returns the raw MongoDB collection instance for advanced operations
336
- * @returns The MongoDB collection instance
337
- * @throws Error if the store is not provisioned
338
- */
339
- rawCollection(): Collection<this["_type"]>;
340
- /**
341
- * Renames an existing collection to this store's name, used for migrations
342
- * @param oldName - The previous name of the collection
343
- * @throws Error if the old collection doesn't exist or if this store's collection already exists
344
- */
345
- renameFrom(oldName: string, options?: {
346
- session?: ClientSession;
347
- }): Promise<void>;
348
- /**
349
- * Performs a vector similarity search using MongoDB Atlas Vector Search
350
- *
351
- * @param params - Vector search parameters
352
- * @param params.field - The field name containing the vector embeddings
353
- * @param params.embedding - The query vector to search for
354
- * @param params.numCandidates - Number of nearest neighbors to consider (default: 100)
355
- * @param params.limit - Maximum number of results to return (default: 10)
356
- * @param params.projection - Additional fields to include in the results
357
- * @param params.indexName - Name of index (default: field + VectorSearch)
358
- * @returns An aggregation cursor with search results and scores
359
- *
360
- * @example
361
- * ```ts
362
- * const results = await store.vectorSearch({
363
- * field: 'embedding',
364
- * embedding: [0.1, 0.2, 0.3, ...],
365
- * numCandidates: 100,
366
- * limit: 10,
367
- * projection: { title: 1, description: 1 }
368
- * });
369
- * ```
370
- */
371
- vectorSearch({ field, embedding, numCandidates, limit, projection, indexName, }: {
372
- field: string;
373
- embedding: number[];
374
- numCandidates?: number;
375
- limit?: number;
376
- projection?: Document;
377
- indexName?: string;
378
- }): Promise<AggregationCursor<Document>>;
379
- /**
380
- * Creates a MongoDB Atlas Vector Search index definition
381
- *
382
- * @param params - Vector index parameters
383
- * @param params.field - The field name to create the vector index on
384
- * @param params.dimensions - The number of dimensions in the vector embeddings
385
- * @param params.similarity - The similarity metric to use (default: 'cosine')
386
- * @param params.indexName - Name of index (default: field + VectorSearch)
387
- * @returns A search index description object
388
- *
389
- * @example
390
- * ```ts
391
- * const store = new Store('documents', {
392
- * schema: {
393
- * title: schema.string(),
394
- * embedding: schema.array(schema.number()),
395
- * },
396
- * indexes: [],
397
- * searchIndexes: [
398
- * Store.vectorIndex({
399
- * field: 'embedding',
400
- * dimensions: 1536,
401
- * similarity: 'cosine'
402
- * })
403
- * ]
404
- * });
405
- * ```
406
- */
407
- static vectorIndex({ field, dimensions, similarity, indexName, }: {
408
- field: string;
409
- dimensions: number;
410
- similarity?: 'cosine' | 'euclidean' | 'dotProduct';
411
- indexName?: string;
412
- }): {
413
- type: string;
414
- name: string;
415
- definition: {
416
- fields: {
417
- type: string;
418
- path: string;
419
- numDimensions: number;
420
- similarity: "cosine" | "euclidean" | "dotProduct";
421
- }[];
422
- };
423
- };
424
- }
425
-
426
- type ClientInfo = {
427
- screenWidth: number;
428
- screenHeight: number;
429
- windowWidth: number;
430
- windowHeight: number;
431
- pixelRatio: number;
432
- orientation: string | null;
433
- };
434
- type ConnectionInfo = {
435
- ip?: string;
436
- userAgent?: string;
437
- acceptLanguage?: string;
438
- referrer?: string;
439
- baseUrl?: string;
440
- };
441
- type Context = {
442
- session: Session | null;
443
- user: UserInfo | null;
444
- roles: string[];
445
- clientInfo: ClientInfo;
446
- connectionInfo: ConnectionInfo;
447
- };
448
- type Args = Record<string, unknown>;
449
- type Handler<T = unknown> = (args: Args, context: Context) => Promise<T> | T;
450
- type MethodDefinition<T = unknown> = {
451
- permissions?: Permission[];
452
- handler: Handler<T>;
453
- } | Handler<T>;
454
-
455
- type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head' | 'all' | 'use';
456
- type RouteParams<T = unknown> = {
457
- query: Record<string, string>;
458
- body: T;
459
- params: Record<string, string>;
460
- headers: Record<string, string>;
461
- cookies: Record<string, string>;
462
- req: Request;
463
- res: Response;
464
- next: NextFunction;
465
- };
466
- type RouteResponse<T = unknown> = {
467
- data?: T;
468
- status?: number;
469
- headers?: Record<string, string>;
470
- redirect?: string;
471
- } | null;
472
- type RouteHandler<T = unknown> = (params: RouteParams, context: Pick<Context, 'session' | 'user'>) => Promise<RouteResponse<T>> | RouteResponse<T>;
473
- type RouteHandlers = {
474
- [key in HttpMethod]?: RouteHandler;
475
- };
476
- type RouteDefinition = {
477
- path: string;
478
- handlers: RouteHandlers;
479
- errorHandler?: RouteHandler;
480
- };
481
-
482
- type RateLimitType = 'ip' | 'user';
483
- type RateLimitRule = {
484
- /** Logical action being limited, e.g. "signup" */
485
- bucket: string;
486
- /** Identifier type of the actor this rule applies to */
487
- type: RateLimitType;
488
- /** Time window size in milliseconds */
489
- window: number;
490
- /** Maximum allowed hits within the window */
491
- limit: number;
492
- };
493
-
494
11
  /** Array of Store instances that will be provisioned when the module is loaded */
495
12
  type Stores = Store<any, any>[];
496
13
  /** Record of query methods that can be called from the client */
@@ -972,9 +489,6 @@ declare function consumeRateLimit(options: {
972
489
  /**
973
490
  * @sidebarTitle getConfig (server)
974
491
  *
975
- * Retrieves a configuration value by key. Configuration values can be set via environment variables
976
- * or managed through the Modelence Cloud Backend.
977
- *
978
492
  * @param key - The configuration key to retrieve
979
493
  * @returns The configuration value (string, number, or boolean)
980
494
  *
@@ -1035,4 +549,4 @@ declare function authenticate(authToken: string | null): Promise<{
1035
549
 
1036
550
  declare function sendEmail(payload: EmailPayload): Promise<void> | undefined;
1037
551
 
1038
- export { type AppOptions, type AuthConfig, type AuthOption, type CloudBackendConnectResponse, type CronJobInputParams, type HttpMethod, Module, type RateLimitRule, type RateLimitType, type RouteDefinition, type RouteHandler, type RouteParams, type RouteResponse, ServerChannel, Store, UserInfo, authenticate, consumeRateLimit, createQuery, usersCollection as dbUsers, deleteUser, disableUser, getConfig, schema, sendEmail, startApp };
552
+ export { type AppOptions, type AuthConfig, type AuthOption, type CloudBackendConnectResponse, CronJobInputParams, Module, RateLimitRule, RateLimitType, RouteDefinition, ServerChannel, Store, UserInfo, authenticate, consumeRateLimit, createQuery, usersCollection as dbUsers, deleteUser, disableUser, getConfig, sendEmail, startApp };