@zodmon/core 0.9.0 → 0.10.0

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.cts CHANGED
@@ -2977,11 +2977,222 @@ declare function insertOne<TDef extends AnyCollection>(handle: CollectionHandle<
2977
2977
  */
2978
2978
  declare function insertMany<TDef extends AnyCollection>(handle: CollectionHandle<TDef>, docs: InferInsert<TDef>[]): Promise<InferDocument<TDef>[]>;
2979
2979
 
2980
+ /**
2981
+ * Base error class for all Zodmon errors.
2982
+ *
2983
+ * Every error thrown by Zodmon extends this class, making it easy to catch all
2984
+ * Zodmon-related errors in a single `catch` block while still allowing more
2985
+ * specific handling via subclass checks.
2986
+ *
2987
+ * @example
2988
+ * ```ts
2989
+ * try {
2990
+ * await users.insertOne({ name: 123 })
2991
+ * } catch (err) {
2992
+ * if (err instanceof ZodmonError) {
2993
+ * console.log(err.name) // => 'ZodmonError' (or a subclass name)
2994
+ * console.log(err.collection) // => 'users'
2995
+ * console.log(err.cause) // => original Error, if provided
2996
+ * }
2997
+ * }
2998
+ * ```
2999
+ */
3000
+ declare class ZodmonError extends Error {
3001
+ readonly name: string;
3002
+ /** The MongoDB collection name associated with this error. */
3003
+ readonly collection: string;
3004
+ /** The underlying error that caused this error, if any. */
3005
+ readonly cause?: Error;
3006
+ constructor(message: string, collection: string, options?: {
3007
+ cause?: Error;
3008
+ });
3009
+ }
3010
+
3011
+ /**
3012
+ * Thrown when MongoDB rejects an operation due to authentication or authorization failure.
3013
+ *
3014
+ * Corresponds to MongoDB error codes 13 (Unauthorized) and 18 (AuthenticationFailed).
3015
+ * Inspect `.code` to distinguish between authorization and authentication failures.
3016
+ *
3017
+ * @example
3018
+ * ```ts
3019
+ * try {
3020
+ * await users.insertOne({ name: 'Alice' })
3021
+ * } catch (err) {
3022
+ * if (err instanceof ZodmonAuthError) {
3023
+ * console.log(err.message) // => 'Not authorized to perform this operation on "users"'
3024
+ * console.log(err.code) // => 13 or 18
3025
+ * console.log(err.collection) // => 'users'
3026
+ * }
3027
+ * }
3028
+ * ```
3029
+ */
3030
+ declare class ZodmonAuthError extends ZodmonError {
3031
+ readonly name = "ZodmonAuthError";
3032
+ /** The MongoDB error code (13 or 18). */
3033
+ readonly code: number;
3034
+ constructor(collection: string, code: number, cause: Error);
3035
+ }
3036
+
3037
+ /**
3038
+ * Thrown when a bulk write operation partially or fully fails.
3039
+ *
3040
+ * Exposes partial result counts (`.insertedCount`, `.matchedCount`, etc.) alongside
3041
+ * an array of `.writeErrors` describing each individual failure. Use this to determine
3042
+ * which operations succeeded and which failed.
3043
+ *
3044
+ * @example
3045
+ * ```ts
3046
+ * try {
3047
+ * await users.insertMany([{ name: 'Alice' }, { name: 'Alice' }]) // duplicate
3048
+ * } catch (err) {
3049
+ * if (err instanceof ZodmonBulkWriteError) {
3050
+ * console.log(err.insertedCount) // => 1
3051
+ * console.log(err.writeErrors) // => [{ index: 1, code: 11000, message: '...' }]
3052
+ * console.log(err.collection) // => 'users'
3053
+ * }
3054
+ * }
3055
+ * ```
3056
+ */
3057
+ declare class ZodmonBulkWriteError extends ZodmonError {
3058
+ readonly name = "ZodmonBulkWriteError";
3059
+ /** Number of documents successfully inserted. */
3060
+ readonly insertedCount: number;
3061
+ /** Number of documents matched by update filters. */
3062
+ readonly matchedCount: number;
3063
+ /** Number of documents actually modified. */
3064
+ readonly modifiedCount: number;
3065
+ /** Number of documents deleted. */
3066
+ readonly deletedCount: number;
3067
+ /** Individual write errors with their operation index, code, and message. */
3068
+ readonly writeErrors: Array<{
3069
+ index: number;
3070
+ code: number;
3071
+ message: string;
3072
+ }>;
3073
+ constructor(collection: string, cause: Error, totalOps?: number);
3074
+ }
3075
+
3076
+ /**
3077
+ * Thrown when a document fails server-side JSON Schema validation (MongoDB error code 121).
3078
+ *
3079
+ * This is distinct from {@link ZodmonValidationError}, which validates against Zod schemas
3080
+ * on the client side. This error surfaces when MongoDB's own document validation rejects
3081
+ * a write. Inspect `.errInfo` for the server's detailed validation failure information.
3082
+ *
3083
+ * @example
3084
+ * ```ts
3085
+ * try {
3086
+ * await users.insertOne({ name: 'Alice', age: -1 })
3087
+ * } catch (err) {
3088
+ * if (err instanceof ZodmonDocValidationError) {
3089
+ * console.log(err.message) // => 'Server-side document validation failed for "users": ...'
3090
+ * console.log(err.errInfo) // => { failingDocumentId: ..., details: ... }
3091
+ * console.log(err.collection) // => 'users'
3092
+ * }
3093
+ * }
3094
+ * ```
3095
+ */
3096
+ declare class ZodmonDocValidationError extends ZodmonError {
3097
+ readonly name = "ZodmonDocValidationError";
3098
+ /** Server-provided validation failure details. */
3099
+ readonly errInfo: unknown;
3100
+ constructor(collection: string, errInfo: unknown, cause: Error);
3101
+ }
3102
+
3103
+ /**
3104
+ * Thrown when a MongoDB insert or update violates a unique index constraint (E11000).
3105
+ *
3106
+ * Parses the duplicate key information from the MongoDB driver error to expose
3107
+ * structured fields: `.field` (first conflicting key), `.value`, `.index` (index name),
3108
+ * `.keyPattern`, and `.keyValue`. Falls back to regex parsing for older drivers.
3109
+ *
3110
+ * @example
3111
+ * ```ts
3112
+ * try {
3113
+ * await users.insertOne({ email: 'alice@example.com' })
3114
+ * } catch (err) {
3115
+ * if (err instanceof ZodmonDuplicateKeyError) {
3116
+ * console.log(err.field) // => 'email'
3117
+ * console.log(err.value) // => 'alice@example.com'
3118
+ * console.log(err.index) // => 'email_1'
3119
+ * console.log(err.keyPattern) // => { email: 1 }
3120
+ * console.log(err.keyValue) // => { email: 'alice@example.com' }
3121
+ * console.log(err.collection) // => 'users'
3122
+ * }
3123
+ * }
3124
+ * ```
3125
+ */
3126
+ declare class ZodmonDuplicateKeyError extends ZodmonError {
3127
+ readonly name = "ZodmonDuplicateKeyError";
3128
+ /** The first field that caused the duplicate key violation. */
3129
+ readonly field: string;
3130
+ /** The duplicate value, or `undefined` if it could not be extracted. */
3131
+ readonly value: unknown;
3132
+ /** The name of the index that was violated. */
3133
+ readonly index: string;
3134
+ /** The key pattern of the violated index (e.g. `{ email: 1 }`). */
3135
+ readonly keyPattern: Record<string, number>;
3136
+ /** The key values that caused the violation. */
3137
+ readonly keyValue: Record<string, unknown>;
3138
+ constructor(collection: string, cause: Error);
3139
+ }
3140
+
3141
+ /**
3142
+ * Thrown when a MongoDB index operation fails.
3143
+ *
3144
+ * Corresponds to MongoDB error codes 67 (CannotCreateIndex), 85 (IndexOptionsConflict),
3145
+ * and 86 (IndexKeySpecsConflict). Inspect `.code` to determine the specific failure reason.
3146
+ *
3147
+ * @example
3148
+ * ```ts
3149
+ * try {
3150
+ * await syncIndexes(db, [Users])
3151
+ * } catch (err) {
3152
+ * if (err instanceof ZodmonIndexError) {
3153
+ * console.log(err.message) // => 'Index options conflict on "users": ...'
3154
+ * console.log(err.code) // => 67, 85, or 86
3155
+ * console.log(err.collection) // => 'users'
3156
+ * }
3157
+ * }
3158
+ * ```
3159
+ */
3160
+ declare class ZodmonIndexError extends ZodmonError {
3161
+ readonly name = "ZodmonIndexError";
3162
+ /** The MongoDB error code (67, 85, or 86). */
3163
+ readonly code: number;
3164
+ constructor(collection: string, code: number, errmsg: string, cause: Error);
3165
+ }
3166
+
3167
+ /**
3168
+ * Thrown when a MongoDB operation fails due to a network error.
3169
+ *
3170
+ * Wraps `MongoNetworkError` from the MongoDB driver with the collection name
3171
+ * and the original error message for easier debugging.
3172
+ *
3173
+ * @example
3174
+ * ```ts
3175
+ * try {
3176
+ * await users.find({ status: 'active' })
3177
+ * } catch (err) {
3178
+ * if (err instanceof ZodmonNetworkError) {
3179
+ * console.log(err.message) // => 'Network error on "users": connection refused'
3180
+ * console.log(err.collection) // => 'users'
3181
+ * }
3182
+ * }
3183
+ * ```
3184
+ */
3185
+ declare class ZodmonNetworkError extends ZodmonError {
3186
+ readonly name = "ZodmonNetworkError";
3187
+ constructor(collection: string, cause: Error);
3188
+ }
3189
+
2980
3190
  /**
2981
3191
  * Thrown when a query expected to find a document returns no results.
2982
3192
  *
2983
3193
  * Used by {@link findOneOrThrow} when no document matches the provided filter.
2984
- * Callers can inspect `.collection` to identify which collection the query targeted.
3194
+ * Callers can inspect `.collection` to identify which collection the query targeted,
3195
+ * and `.filter` to see the query that produced no results.
2985
3196
  *
2986
3197
  * @example
2987
3198
  * ```ts
@@ -2991,15 +3202,68 @@ declare function insertMany<TDef extends AnyCollection>(handle: CollectionHandle
2991
3202
  * if (err instanceof ZodmonNotFoundError) {
2992
3203
  * console.log(err.message) // => 'Document not found in "users"'
2993
3204
  * console.log(err.collection) // => 'users'
3205
+ * console.log(err.filter) // => { name: 'nonexistent' }
2994
3206
  * }
2995
3207
  * }
2996
3208
  * ```
2997
3209
  */
2998
- declare class ZodmonNotFoundError extends Error {
3210
+ declare class ZodmonNotFoundError extends ZodmonError {
2999
3211
  readonly name = "ZodmonNotFoundError";
3000
- /** The MongoDB collection name where the query found no results. */
3001
- readonly collection: string;
3002
- constructor(collection: string);
3212
+ /** The filter that produced no results. */
3213
+ readonly filter: unknown;
3214
+ constructor(collection: string, filter: unknown);
3215
+ }
3216
+
3217
+ /**
3218
+ * Thrown when a MongoDB query is malformed or exceeds resource limits.
3219
+ *
3220
+ * Corresponds to MongoDB error codes 2 (BadValue), 9 (FailedToParse), and
3221
+ * 292 (QueryExceededMemoryLimit). Inspect `.code` to determine the specific failure.
3222
+ *
3223
+ * @example
3224
+ * ```ts
3225
+ * try {
3226
+ * await users.find({ $invalid: true })
3227
+ * } catch (err) {
3228
+ * if (err instanceof ZodmonQueryError) {
3229
+ * console.log(err.message) // => 'Bad value in query on "users": ...'
3230
+ * console.log(err.code) // => 2, 9, or 292
3231
+ * console.log(err.collection) // => 'users'
3232
+ * }
3233
+ * }
3234
+ * ```
3235
+ */
3236
+ declare class ZodmonQueryError extends ZodmonError {
3237
+ readonly name = "ZodmonQueryError";
3238
+ /** The MongoDB error code (2, 9, or 292). */
3239
+ readonly code: number;
3240
+ constructor(collection: string, code: number, errmsg: string, cause: Error);
3241
+ }
3242
+
3243
+ /**
3244
+ * Thrown when a MongoDB operation exceeds its server time limit.
3245
+ *
3246
+ * Corresponds to MongoDB error codes 50 (MaxTimeMSExpired) and
3247
+ * 262 (ExceededTimeLimit). Inspect `.code` to distinguish between the two.
3248
+ *
3249
+ * @example
3250
+ * ```ts
3251
+ * try {
3252
+ * await users.find({ status: 'active' })
3253
+ * } catch (err) {
3254
+ * if (err instanceof ZodmonTimeoutError) {
3255
+ * console.log(err.message) // => 'Operation timed out on "users": ...'
3256
+ * console.log(err.code) // => 50 or 262
3257
+ * console.log(err.collection) // => 'users'
3258
+ * }
3259
+ * }
3260
+ * ```
3261
+ */
3262
+ declare class ZodmonTimeoutError extends ZodmonError {
3263
+ readonly name = "ZodmonTimeoutError";
3264
+ /** The MongoDB error code (50 or 262). */
3265
+ readonly code: number;
3266
+ constructor(collection: string, code: number, cause: Error);
3003
3267
  }
3004
3268
 
3005
3269
  /**
@@ -3019,17 +3283,62 @@ declare class ZodmonNotFoundError extends Error {
3019
3283
  * // => 'Validation failed for "users": name (Expected string, received number)'
3020
3284
  * console.log(err.collection) // => 'users'
3021
3285
  * console.log(err.zodError) // => ZodError with .issues array
3286
+ * console.log(err.document) // => the document that failed validation
3022
3287
  * }
3023
3288
  * }
3024
3289
  * ```
3025
3290
  */
3026
- declare class ZodmonValidationError extends Error {
3291
+ declare class ZodmonValidationError extends ZodmonError {
3027
3292
  readonly name = "ZodmonValidationError";
3028
- /** The MongoDB collection name where the validation failed. */
3029
- readonly collection: string;
3030
3293
  /** The original Zod validation error with detailed issue information. */
3031
3294
  readonly zodError: z.ZodError;
3032
- constructor(collection: string, zodError: z.ZodError);
3295
+ /** The document that failed validation. */
3296
+ readonly document: unknown;
3297
+ constructor(collection: string, zodError: z.ZodError, document: unknown);
3298
+ }
3299
+
3300
+ /**
3301
+ * Maps a caught MongoDB error to the appropriate Zodmon error subclass and throws it.
3302
+ *
3303
+ * This function always throws — it never returns. Use it in `catch` blocks to convert
3304
+ * raw MongoDB driver errors into structured, typed Zodmon errors. If the error is already
3305
+ * a `ZodmonError`, it is rethrown as-is to prevent double-wrapping.
3306
+ *
3307
+ * @example
3308
+ * ```ts
3309
+ * try {
3310
+ * await db.collection('users').insertOne(doc)
3311
+ * } catch (err) {
3312
+ * wrapMongoError(err, 'users')
3313
+ * }
3314
+ * ```
3315
+ */
3316
+ declare function wrapMongoError(err: unknown, collection: string): never;
3317
+
3318
+ /**
3319
+ * Thrown when a transaction encounters a write conflict (MongoDB error code 112).
3320
+ *
3321
+ * This occurs when another operation modifies the same document concurrently during
3322
+ * a transaction. The recommended recovery strategy is to retry the transaction.
3323
+ *
3324
+ * @example
3325
+ * ```ts
3326
+ * try {
3327
+ * await db.transaction(async (tx) => {
3328
+ * const users = tx.use(Users)
3329
+ * await users.updateOne({ _id: id }, { $inc: { balance: -100 } })
3330
+ * })
3331
+ * } catch (err) {
3332
+ * if (err instanceof ZodmonWriteConflictError) {
3333
+ * console.log(err.message) // => 'Write conflict in "users": ...'
3334
+ * console.log(err.collection) // => 'users'
3335
+ * }
3336
+ * }
3337
+ * ```
3338
+ */
3339
+ declare class ZodmonWriteConflictError extends ZodmonError {
3340
+ readonly name = "ZodmonWriteConflictError";
3341
+ constructor(collection: string, cause: Error);
3033
3342
  }
3034
3343
 
3035
3344
  /**
@@ -3609,4 +3918,4 @@ type UpdateFilterOf<TDef extends AnyCollection> = TypedUpdateFilter<InferDocumen
3609
3918
  */
3610
3919
  type SortOf<TDef extends AnyCollection> = TypedSort<InferDocument<TDef>>;
3611
3920
 
3612
- export { $, $addToSet, $and, $avg, $count, $eq, $exists, $first, $gt, $gte, $in, $last, $lt, $lte, $max, $min, $ne, $nin, $nor, $not, $or, $push, $regex, $sum, type Accumulator, type AccumulatorBuilder, type AddToSetEach, type AddToSetFields, AggregatePipeline, type AnyCollection, type ArrayElement, type CollectionDefinition, CollectionHandle, type CollectionName, type CollectionOptions, type ComparisonOperators, type CompoundIndexDefinition, type CurrentDateFields, type CursorPage, type CursorPaginateOptions, Database, type DotPathType, type DotPaths, type Expression, type ExpressionBuilder, type ExtractRefCollection, type FieldIndexDefinition, type FieldRef, type FieldRefType, type FilterOf, type FindOneAndDeleteOptions, type FindOneAndUpdateOptions, type FindOneOptions, type FindOptions, type GroupByCompoundResult, type GroupByResult, type HandleOf, type IncFields, IndexBuilder, type IndexMetadata, type IndexNames, type IndexOptions, type IndexSpec, type InferAccumulator, type InferAccumulators, type InferAddedFields, type InferDocument, type InferExpression, type InferInsert, type NarrowFromFilter, type OffsetPage, type OffsetPaginateOptions, type PopFields, type Prettify, type PullFields, type PushFields, type PushModifiers, type RefFields, type RefMarker, type RefMetadata, type RenameFields, type ResolvedShape, type SetFields, type SortOf, type StaleIndex, type SyncIndexesOptions, type SyncIndexesResult, type TypedFilter, TypedFindCursor, type TypedSort, type TypedUpdateFilter, type UnsetFields, type UnwindResult, type UpdateFilterOf, type UpdateOptions, type ValidationMode, type ZodObjectId, ZodmonNotFoundError, ZodmonValidationError, aggregate, checkUnindexedFields, collection, createAccumulatorBuilder, createClient, createExpressionBuilder, deleteMany, deleteOne, extractComparableOptions, extractDbName, extractFieldIndexes, find, findOne, findOneAndDelete, findOneAndUpdate, findOneOrThrow, generateIndexName, getIndexMetadata, getRefMetadata, index, insertMany, insertOne, isOid, objectId, oid, raw, serializeIndexKey, syncIndexes, toCompoundIndexSpec, toFieldIndexSpec, updateMany, updateOne };
3921
+ export { $, $addToSet, $and, $avg, $count, $eq, $exists, $first, $gt, $gte, $in, $last, $lt, $lte, $max, $min, $ne, $nin, $nor, $not, $or, $push, $regex, $sum, type Accumulator, type AccumulatorBuilder, type AddToSetEach, type AddToSetFields, AggregatePipeline, type AnyCollection, type ArrayElement, type CollectionDefinition, CollectionHandle, type CollectionName, type CollectionOptions, type ComparisonOperators, type CompoundIndexDefinition, type CurrentDateFields, type CursorPage, type CursorPaginateOptions, Database, type DotPathType, type DotPaths, type Expression, type ExpressionBuilder, type ExtractRefCollection, type FieldIndexDefinition, type FieldRef, type FieldRefType, type FilterOf, type FindOneAndDeleteOptions, type FindOneAndUpdateOptions, type FindOneOptions, type FindOptions, type GroupByCompoundResult, type GroupByResult, type HandleOf, type IncFields, IndexBuilder, type IndexMetadata, type IndexNames, type IndexOptions, type IndexSpec, type InferAccumulator, type InferAccumulators, type InferAddedFields, type InferDocument, type InferExpression, type InferInsert, type NarrowFromFilter, type OffsetPage, type OffsetPaginateOptions, type PopFields, type Prettify, type PullFields, type PushFields, type PushModifiers, type RefFields, type RefMarker, type RefMetadata, type RenameFields, type ResolvedShape, type SetFields, type SortOf, type StaleIndex, type SyncIndexesOptions, type SyncIndexesResult, type TypedFilter, TypedFindCursor, type TypedSort, type TypedUpdateFilter, type UnsetFields, type UnwindResult, type UpdateFilterOf, type UpdateOptions, type ValidationMode, type ZodObjectId, ZodmonAuthError, ZodmonBulkWriteError, ZodmonDocValidationError, ZodmonDuplicateKeyError, ZodmonError, ZodmonIndexError, ZodmonNetworkError, ZodmonNotFoundError, ZodmonQueryError, ZodmonTimeoutError, ZodmonValidationError, ZodmonWriteConflictError, aggregate, checkUnindexedFields, collection, createAccumulatorBuilder, createClient, createExpressionBuilder, deleteMany, deleteOne, extractComparableOptions, extractDbName, extractFieldIndexes, find, findOne, findOneAndDelete, findOneAndUpdate, findOneOrThrow, generateIndexName, getIndexMetadata, getRefMetadata, index, insertMany, insertOne, isOid, objectId, oid, raw, serializeIndexKey, syncIndexes, toCompoundIndexSpec, toFieldIndexSpec, updateMany, updateOne, wrapMongoError };