mongo-type-safe 1.0.6 → 2.0.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/CHANGELOG.md +38 -0
- package/README.md +176 -2
- package/dist/index.d.ts +73 -0
- package/dist/index.js +11 -13
- package/dist/types/filter.d.ts +29 -0
- package/dist/types/filter.js +7 -0
- package/dist/types/paths.d.ts +18 -0
- package/dist/types/paths.js +5 -0
- package/dist/types/update.d.ts +27 -0
- package/dist/types/update.js +4 -0
- package/dist/util/helper.d.ts +5 -0
- package/dist/util/helper.js +5 -35
- package/dist/util/types.d.ts +6 -0
- package/dist/util/types.js +2 -16
- package/dist/util/validate.d.ts +5 -0
- package/dist/util/validate.js +5 -51
- package/dist/validation/filter-schema.d.ts +3 -0
- package/dist/validation/filter-schema.js +47 -0
- package/dist/validation/schema-paths.d.ts +9 -0
- package/dist/validation/schema-paths.js +69 -0
- package/dist/validation/schema-types.d.ts +8 -0
- package/dist/validation/schema-types.js +55 -0
- package/dist/validation/update-fields.d.ts +9 -0
- package/dist/validation/update-fields.js +49 -0
- package/dist/validation/update.d.ts +4 -0
- package/dist/validation/update.js +89 -0
- package/package.json +49 -42
- package/mongo-type-safe-1.0.0.tgz +0 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 2.0.0 — 2026-11-30
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Typed dotted object paths for filters across reads, updates, deletes, replacements and counts.
|
|
8
|
+
- Typed nested `$set`, `$inc`, `$unset`, `$min`, `$max` and `$setOnInsert` payloads.
|
|
9
|
+
- Public `FieldPath`, `PathValue`, `UpdateFieldPath`, `TypedFilter` and `SafeUpdate` types.
|
|
10
|
+
- Compile-time regression tests and integration tests for nested filters and updates.
|
|
11
|
+
- Published TypeScript declarations and a prepack check that builds the package.
|
|
12
|
+
|
|
13
|
+
### Changed
|
|
14
|
+
|
|
15
|
+
- All collection methods use the same filter type and validate supported paths consistently.
|
|
16
|
+
- Validated update assignments use the parsed Zod values without mutating the caller's payload.
|
|
17
|
+
- Field traversal is limited to eight path segments. Arrays and dynamic records remain atomic values.
|
|
18
|
+
- `$min` and `$max` support matching non-nullable strings, numbers and dates.
|
|
19
|
+
|
|
20
|
+
### Breaking changes and migration
|
|
21
|
+
|
|
22
|
+
- Unknown update paths, incorrect operands and conflicting update paths are rejected.
|
|
23
|
+
The permissive MongoDB driver index signatures no longer allow arbitrary update keys.
|
|
24
|
+
- `$unset` accepts only optional fields and the markers `""`, `1` and `true`.
|
|
25
|
+
A nullable field or a required child of an optional parent cannot be removed.
|
|
26
|
+
A defaulted output field remains required unless an outer `.optional()` is present.
|
|
27
|
+
- `_id` is writable only through `$setOnInsert` when explicitly modeled in the schema.
|
|
28
|
+
- `$inc` accepts finite numeric deltas for non-nullable numeric fields. It does not
|
|
29
|
+
validate the final stored value against numeric bounds or cross-field constraints.
|
|
30
|
+
- Replace union-valued objects as a whole; updating independent variant paths is not supported.
|
|
31
|
+
- Use field-level `$not` or `$nor`. The previously accepted top-level `$not` shape is rejected.
|
|
32
|
+
- Explicit `undefined` assignments are rejected at runtime; use `$unset` for optional fields.
|
|
33
|
+
- Zod parsing may normalize update values, apply defaults, or strip unknown object properties
|
|
34
|
+
according to the supplied schema. `strict: false` still bypasses runtime parsing and validation.
|
|
35
|
+
|
|
36
|
+
This release uses Zod 3 and MongoDB Node.js driver 6. TypeScript assignment types
|
|
37
|
+
describe stored output values. Update validation checks the patch, not the final
|
|
38
|
+
document; enforce final-document invariants in the database or application.
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# mongo-type-safe
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Get compile-time safety for all your MongoDB CRUD operations, plus optional runtime validation using Zod. Runtime checks are enabled by default for extra safety, but can be disabled for zero runtime overhead.
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -10,15 +10,20 @@ A type-safe MongoDB wrapper for Node.js using Zod schemas and TypeScript. Get co
|
|
|
10
10
|
- **Zod integration**: Use your Zod schemas as the single source of truth
|
|
11
11
|
- **With runtime validation**: Enforces schema correctness at both compile-time and runtime using Zod.
|
|
12
12
|
- **Familiar API**: Mirrors the official MongoDB Node.js driver
|
|
13
|
+
- **Typed nested filters**: Check dotted object paths and their values in TypeScript and at runtime
|
|
14
|
+
- **Typed nested updates**: Validate assignments, numeric increments and removal of optional fields
|
|
13
15
|
|
|
14
16
|
---
|
|
15
17
|
|
|
16
18
|
## Installation
|
|
17
19
|
|
|
18
20
|
```bash
|
|
19
|
-
npm install mongo-type-safe zod mongodb
|
|
21
|
+
npm install mongo-type-safe zod@^3.25.75 mongodb@^6.17.0
|
|
20
22
|
```
|
|
21
23
|
|
|
24
|
+
Version 2 uses **Zod 3** and the **MongoDB Node.js driver 6**. Zod 4 schemas are
|
|
25
|
+
not supported by this release. See [CHANGELOG.md](./CHANGELOG.md) for migration notes.
|
|
26
|
+
|
|
22
27
|
---
|
|
23
28
|
|
|
24
29
|
## Quick Start
|
|
@@ -206,6 +211,175 @@ See the source for full method signatures and JSDoc documentation.
|
|
|
206
211
|
|
|
207
212
|
---
|
|
208
213
|
|
|
214
|
+
## Typed nested filters
|
|
215
|
+
|
|
216
|
+
Use MongoDB dot notation to query a field inside an embedded object. The path
|
|
217
|
+
and its value are checked against your Zod schema:
|
|
218
|
+
|
|
219
|
+
```typescript
|
|
220
|
+
import { z } from "zod";
|
|
221
|
+
import { createSafeCollection, type TypedFilter } from "mongo-type-safe";
|
|
222
|
+
|
|
223
|
+
const schema = z.object({
|
|
224
|
+
profile: z.object({
|
|
225
|
+
address: z.object({ city: z.string() })
|
|
226
|
+
}).optional(),
|
|
227
|
+
stats: z.object({ views: z.number() })
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
const users = createSafeCollection(db.collection<z.infer<typeof schema>>("users"), schema);
|
|
231
|
+
|
|
232
|
+
const filter: TypedFilter<z.infer<typeof schema>> = {
|
|
233
|
+
"profile.address.city": { $in: ["Bar", "Podgorica"] },
|
|
234
|
+
"stats.views": { $gte: 10 }
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
await users.find(filter).toArray();
|
|
238
|
+
await users.countDocuments({ "profile.address.city": "Bar" });
|
|
239
|
+
await users.updateMany(filter, { $set: { stats: { views: 20 } } });
|
|
240
|
+
|
|
241
|
+
// TypeScript errors: unknown path and incorrect value type.
|
|
242
|
+
// users.find({ "profile.address.citty": "Bar" });
|
|
243
|
+
// users.find({ "stats.views": { $gte: "ten" } });
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
The same filter type is used by every method that accepts a filter, including
|
|
247
|
+
updates, deletes, replacements, counts and the filter argument of `distinct`.
|
|
248
|
+
With `strict: true`, invalid paths and operands are rejected before calling the
|
|
249
|
+
MongoDB driver. With `strict: false`, TypeScript checking remains enabled.
|
|
250
|
+
|
|
251
|
+
### Operators
|
|
252
|
+
|
|
253
|
+
- All fields: `$eq`, `$ne`, `$in`, `$nin`, `$exists` and field-level `$not`.
|
|
254
|
+
- Strings, numbers and dates: `$gt`, `$gte`, `$lt` and `$lte`.
|
|
255
|
+
- Strings: `$regex` with a `RegExp` operand.
|
|
256
|
+
- Logical groups: nonempty `$and`, `$or` and `$nor` arrays, including nested groups.
|
|
257
|
+
|
|
258
|
+
```typescript
|
|
259
|
+
await users.find({
|
|
260
|
+
$or: [
|
|
261
|
+
{ "profile.address.city": { $regex: /^Bar$/ } },
|
|
262
|
+
{ "stats.views": { $not: { $lt: 100 } } }
|
|
263
|
+
]
|
|
264
|
+
}).toArray();
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
`$not` belongs inside a field condition. Earlier versions accepted top-level
|
|
268
|
+
`$not` during validation, although MongoDB does not support that query shape.
|
|
269
|
+
Use a field-level `$not` or a `$nor` group instead. Unknown field operators are
|
|
270
|
+
now rejected consistently, including in later logical branches.
|
|
271
|
+
|
|
272
|
+
### Scope and limits
|
|
273
|
+
|
|
274
|
+
- Paths contain at most **eight segments**, including the top-level field.
|
|
275
|
+
This bounds recursive schemas and TypeScript's type expansion.
|
|
276
|
+
- Plain object fields support optional, nullable, default, catch, branded,
|
|
277
|
+
readonly, lazy and refinement wrappers. Object unions expose the known paths of their variants.
|
|
278
|
+
- An optional or nullable parent does not make a required leaf nullable.
|
|
279
|
+
Use `$exists` to query missing fields.
|
|
280
|
+
- Arrays, dates, BSON values, maps, sets and dynamic records are leaves.
|
|
281
|
+
Array indices, positional operators and paths through array elements are not supported.
|
|
282
|
+
- Object-valued transforms, preprocessors and intersections are opaque to path
|
|
283
|
+
traversal. Use explicit `z.object` fields for dotted queries.
|
|
284
|
+
- Schema keys containing dots, null characters, or a leading `$`, and empty
|
|
285
|
+
keys, are excluded from dotted paths.
|
|
286
|
+
- Filters are forwarded unchanged. A whole embedded object uses MongoDB's
|
|
287
|
+
document equality semantics; a dotted path matches an individual field.
|
|
288
|
+
- These rules describe **filter arguments**. See below for update payload rules.
|
|
289
|
+
Projection inference, aggregation stages and the `distinct` result key retain their existing APIs.
|
|
290
|
+
|
|
291
|
+
`FieldPath<T>` and `PathValue<T, Path>` are also exported for reusable query utilities.
|
|
292
|
+
|
|
293
|
+
## Typed nested updates
|
|
294
|
+
|
|
295
|
+
`updateOne`, `updateMany` and `findOneAndUpdate` accept typed dotted paths in
|
|
296
|
+
atomic update documents. For a schema with `profile.address.city: z.string()`,
|
|
297
|
+
`profile.bio: z.string().optional()` and `stats.views: z.number()`:
|
|
298
|
+
|
|
299
|
+
```typescript
|
|
300
|
+
await users.updateOne(
|
|
301
|
+
{ "profile.address.city": "Bar" },
|
|
302
|
+
{
|
|
303
|
+
$set: { "profile.address.city": "Budva" },
|
|
304
|
+
$inc: { "stats.views": 1 },
|
|
305
|
+
$unset: { "profile.bio": "" }
|
|
306
|
+
}
|
|
307
|
+
);
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
The exported `SafeUpdate<T>` type can be used for reusable updates.
|
|
311
|
+
`UpdateFieldPath<T>` exposes the supported paths without the driver's permissive
|
|
312
|
+
string index signatures.
|
|
313
|
+
|
|
314
|
+
### Update rules
|
|
315
|
+
|
|
316
|
+
| Operator | Supported fields and values |
|
|
317
|
+
| --- | --- |
|
|
318
|
+
| `$set` | Known paths with values matching the field schema |
|
|
319
|
+
| `$inc` | Non-nullable numeric fields; a finite positive, negative or zero numeric delta |
|
|
320
|
+
| `$unset` | Optional fields only; use `""`, `1` or `true` as the marker |
|
|
321
|
+
| `$setOnInsert` | Known paths with matching values, including an explicitly modeled `_id` |
|
|
322
|
+
| `$min`, `$max` | Non-nullable string, number or date fields with matching values |
|
|
323
|
+
|
|
324
|
+
An optional parent does not make a required child optional: you may remove an
|
|
325
|
+
optional `profile` object, but not its required `profile.address.city` field.
|
|
326
|
+
Nullable fields remain required unless they are also optional. Fields with Zod
|
|
327
|
+
defaults are required in the stored output and cannot be removed with `$unset`.
|
|
328
|
+
An outer `.optional()` makes a defaulted field optional again.
|
|
329
|
+
|
|
330
|
+
`_id` is immutable outside `$setOnInsert`. Empty operator payloads, such as
|
|
331
|
+
`{ $set: {} }`, are accepted as no-ops; an empty update document `{}` is rejected.
|
|
332
|
+
Runtime validation also rejects overlapping paths, both across operators and
|
|
333
|
+
within a single operator. For example, updating `profile` and
|
|
334
|
+
`profile.address.city` together is a conflict.
|
|
335
|
+
|
|
336
|
+
### Parsing and limitations
|
|
337
|
+
|
|
338
|
+
With runtime validation enabled, assignment values are parsed with their Zod
|
|
339
|
+
field schemas. The parsed values, including supported defaults and transforms,
|
|
340
|
+
are sent to MongoDB in a new update object; the caller's object is not mutated.
|
|
341
|
+
Unknown dotted paths are rejected. For whole-object replacements, the original
|
|
342
|
+
Zod schema controls whether unknown properties are stripped or rejected.
|
|
343
|
+
|
|
344
|
+
TypeScript assignment types describe stored output values, as in the existing
|
|
345
|
+
insert API. Type-changing transforms therefore need schemas whose accepted
|
|
346
|
+
inputs also cover those values. Explicit `undefined` values are rejected at
|
|
347
|
+
runtime; use `$unset` for optional fields. TypeScript's treatment of explicit
|
|
348
|
+
`undefined` in optional properties depends on `exactOptionalPropertyTypes` in
|
|
349
|
+
the consuming project's configuration.
|
|
350
|
+
|
|
351
|
+
Update paths use the same eight-segment limit as filters. Arrays and dynamic
|
|
352
|
+
records can be replaced as a whole; element/index/positional updates are not
|
|
353
|
+
supported. Union-valued fields must also be replaced as a whole, so a dotted
|
|
354
|
+
write cannot independently change a variant's discriminator or payload.
|
|
355
|
+
|
|
356
|
+
Validation checks the patch, without reading existing documents. It cannot
|
|
357
|
+
guarantee the final document satisfies numeric bounds, cross-field refinements
|
|
358
|
+
or all required fields during an upsert. For example, an increment delta is not
|
|
359
|
+
checked against the counter's minimum: a field with `.min(10)` can be incremented
|
|
360
|
+
by `1`. MongoDB may reject traversal through a stored `null` parent. Use database
|
|
361
|
+
validation or application-level checks when final-document invariants matter.
|
|
362
|
+
|
|
363
|
+
`strict: false` bypasses runtime update validation and parsing and forwards the
|
|
364
|
+
original update object. Compile-time checking remains enabled.
|
|
365
|
+
|
|
366
|
+
## Development checks
|
|
367
|
+
|
|
368
|
+
```bash
|
|
369
|
+
npm ci
|
|
370
|
+
npm run build
|
|
371
|
+
npm run test:types
|
|
372
|
+
npm run test:unit
|
|
373
|
+
```
|
|
374
|
+
|
|
375
|
+
`test:types` checks valid calls and calls marked with `@ts-expect-error`; it fails
|
|
376
|
+
if an invalid path or value stops producing a compiler error. The build emits
|
|
377
|
+
JavaScript and `.d.ts` declarations into `dist`.
|
|
378
|
+
|
|
379
|
+
Run `npm test -- --runInBand` for the complete suite. Integration tests require
|
|
380
|
+
a local MongoDB instance on `mongodb://localhost:27017`. The original integration
|
|
381
|
+
tests modify the `test-db` database; use a disposable test server.
|
|
382
|
+
|
|
209
383
|
## Zod Integration
|
|
210
384
|
|
|
211
385
|
- Use your Zod schemas to define the shape of your documents.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { Collection, InsertOneOptions, UpdateOptions, OptionalUnlessRequiredId, Document, FindOptions, FindOneAndReplaceOptions, ReplaceOptions, FindOneAndUpdateOptions, AggregateOptions, FindOneAndDeleteOptions, CountDocumentsOptions, EstimatedDocumentCountOptions } from "mongodb";
|
|
2
|
+
import type { AnyZodObject, TypeOf } from "zod";
|
|
3
|
+
import { CreateSafeCollectionOptions, SafeUpdate, TypedFilter } from "./util/types";
|
|
4
|
+
export type { FieldPath, PathValue, UpdateFieldPath } from "./types/paths";
|
|
5
|
+
export type { TypedFilter, FilterOperators } from "./types/filter";
|
|
6
|
+
export type { SafeUpdate } from "./types/update";
|
|
7
|
+
export declare function createSafeCollection<TSchema extends AnyZodObject>(collection: Collection<TypeOf<TSchema>>, schema: TSchema, { strict }?: CreateSafeCollectionOptions): {
|
|
8
|
+
/**
|
|
9
|
+
* Inserts a single document into the collection.
|
|
10
|
+
*/
|
|
11
|
+
insertOne(doc: OptionalUnlessRequiredId<TypeOf<TSchema>>, options?: InsertOneOptions): Promise<import("mongodb").InsertOneResult<TypeOf<TSchema>>>;
|
|
12
|
+
/**
|
|
13
|
+
* Inserts multiple documents into the collection.
|
|
14
|
+
*/
|
|
15
|
+
insertMany(docs: OptionalUnlessRequiredId<TypeOf<TSchema>>[]): Promise<import("mongodb").InsertManyResult<TypeOf<TSchema>>>;
|
|
16
|
+
/**
|
|
17
|
+
* Updates a single document matching the filter.
|
|
18
|
+
*/
|
|
19
|
+
updateOne(filter: TypedFilter<TypeOf<TSchema>>, update: SafeUpdate<TypeOf<TSchema>>, options?: UpdateOptions): Promise<import("mongodb").UpdateResult<TypeOf<TSchema>>>;
|
|
20
|
+
/**
|
|
21
|
+
* Updates a single document matching the filter and returns it (before or after update).
|
|
22
|
+
*/
|
|
23
|
+
findOneAndUpdate(filter: TypedFilter<TypeOf<TSchema>>, update: SafeUpdate<TypeOf<TSchema>>, options?: FindOneAndUpdateOptions): Promise<import("mongodb").WithId<TypeOf<TSchema>> | null>;
|
|
24
|
+
/**
|
|
25
|
+
* Updates multiple documents matching the filter.
|
|
26
|
+
*/
|
|
27
|
+
updateMany(filter: TypedFilter<TypeOf<TSchema>>, update: SafeUpdate<TypeOf<TSchema>>, options?: UpdateOptions): Promise<import("mongodb").UpdateResult<TypeOf<TSchema>>>;
|
|
28
|
+
/**
|
|
29
|
+
* Finds a single document matching the filter.
|
|
30
|
+
*/
|
|
31
|
+
findOne(filter: TypedFilter<TypeOf<TSchema>>, options?: FindOptions<TypeOf<TSchema>>): Promise<TypeOf<TSchema> | null>;
|
|
32
|
+
/**
|
|
33
|
+
* Finds all documents matching the filter.
|
|
34
|
+
*/
|
|
35
|
+
find(filter: TypedFilter<TypeOf<TSchema>>, options?: FindOptions<TypeOf<TSchema>>): import("mongodb").FindCursor<import("mongodb").WithId<TypeOf<TSchema>>>;
|
|
36
|
+
/**
|
|
37
|
+
* Deletes a single document matching the filter.
|
|
38
|
+
*/
|
|
39
|
+
deleteOne(filter: TypedFilter<TypeOf<TSchema>>, options?: FindOptions<TypeOf<TSchema>>): Promise<import("mongodb").DeleteResult>;
|
|
40
|
+
/**
|
|
41
|
+
* Deletes multiple documents matching the filter.
|
|
42
|
+
*/
|
|
43
|
+
deleteMany(filter: TypedFilter<TypeOf<TSchema>>, options?: FindOptions<TypeOf<TSchema>>): Promise<import("mongodb").DeleteResult>;
|
|
44
|
+
/**
|
|
45
|
+
* Deletes a single document matching the filter and returns it.
|
|
46
|
+
*/
|
|
47
|
+
findOneAndDelete(filter: TypedFilter<TypeOf<TSchema>>, options?: FindOneAndDeleteOptions): Promise<import("mongodb").WithId<TypeOf<TSchema>> | null>;
|
|
48
|
+
/**
|
|
49
|
+
* Replaces a single document matching the filter with a new document.
|
|
50
|
+
*/
|
|
51
|
+
replaceOne(filter: TypedFilter<TypeOf<TSchema>>, newDocument: TypeOf<TSchema>, options?: ReplaceOptions): Promise<import("mongodb").UpdateResult<TypeOf<TSchema>>>;
|
|
52
|
+
/**
|
|
53
|
+
* Finds a single document matching the filter, replaces it with a new document, and returns it.
|
|
54
|
+
*/
|
|
55
|
+
findOneAndReplace(filter: TypedFilter<TypeOf<TSchema>>, newDocument: TypeOf<TSchema>, options?: FindOneAndReplaceOptions): Promise<import("mongodb").WithId<TypeOf<TSchema>> | null>;
|
|
56
|
+
/**
|
|
57
|
+
* Runs an aggregation pipeline on the collection.
|
|
58
|
+
* @template TResult The expected result type of the aggregation.
|
|
59
|
+
*/
|
|
60
|
+
aggregate<TResult extends Document = TypeOf<TSchema> & Document>(pipeline: object[], options?: AggregateOptions): import("mongodb").AggregationCursor<TResult>;
|
|
61
|
+
/**
|
|
62
|
+
* Counts the number of documents matching the filter.
|
|
63
|
+
*/
|
|
64
|
+
countDocuments(filter?: TypedFilter<TypeOf<TSchema>>, options?: CountDocumentsOptions): Promise<number>;
|
|
65
|
+
/**
|
|
66
|
+
* Returns the estimated number of documents in the collection.
|
|
67
|
+
*/
|
|
68
|
+
estimatedDocumentCount(options?: EstimatedDocumentCountOptions): Promise<number>;
|
|
69
|
+
/**
|
|
70
|
+
* Returns an array of distinct values for the given field across a single collection.
|
|
71
|
+
*/
|
|
72
|
+
distinct<Key extends keyof TypeOf<TSchema>>(key: Key, filter?: TypedFilter<TypeOf<TSchema>>): Promise<import("mongodb").Flatten<import("mongodb").WithId<TypeOf<TSchema>>[string]>[]>;
|
|
73
|
+
};
|
package/dist/index.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createSafeCollection = createSafeCollection;
|
|
4
4
|
const validate_1 = require("./util/validate");
|
|
5
|
+
const update_1 = require("./validation/update");
|
|
5
6
|
function createSafeCollection(collection, schema, { strict = true } = {}) {
|
|
6
7
|
return {
|
|
7
8
|
/**
|
|
@@ -24,33 +25,30 @@ function createSafeCollection(collection, schema, { strict = true } = {}) {
|
|
|
24
25
|
* Updates a single document matching the filter.
|
|
25
26
|
*/
|
|
26
27
|
updateOne(filter, update, options) {
|
|
27
|
-
if (strict)
|
|
28
|
+
if (strict)
|
|
28
29
|
(0, validate_1.validateFilter)(filter, schema);
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
return collection.updateOne(filter, update, options);
|
|
30
|
+
const validated = (strict ? (0, update_1.validateUpdate)(update, schema) : update);
|
|
31
|
+
return collection.updateOne(filter, validated, options);
|
|
32
32
|
},
|
|
33
33
|
/**
|
|
34
34
|
* Updates a single document matching the filter and returns it (before or after update).
|
|
35
35
|
*/
|
|
36
36
|
findOneAndUpdate(filter, update, options) {
|
|
37
|
-
if (strict)
|
|
37
|
+
if (strict)
|
|
38
38
|
(0, validate_1.validateFilter)(filter, schema);
|
|
39
|
-
|
|
40
|
-
}
|
|
39
|
+
const validated = (strict ? (0, update_1.validateUpdate)(update, schema) : update);
|
|
41
40
|
return options
|
|
42
|
-
? collection.findOneAndUpdate(filter,
|
|
43
|
-
: collection.findOneAndUpdate(filter,
|
|
41
|
+
? collection.findOneAndUpdate(filter, validated, options)
|
|
42
|
+
: collection.findOneAndUpdate(filter, validated);
|
|
44
43
|
},
|
|
45
44
|
/**
|
|
46
45
|
* Updates multiple documents matching the filter.
|
|
47
46
|
*/
|
|
48
47
|
updateMany(filter, update, options) {
|
|
49
|
-
if (strict)
|
|
48
|
+
if (strict)
|
|
50
49
|
(0, validate_1.validateFilter)(filter, schema);
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
return collection.updateMany(filter, update, options);
|
|
50
|
+
const validated = (strict ? (0, update_1.validateUpdate)(update, schema) : update);
|
|
51
|
+
return collection.updateMany(filter, validated, options);
|
|
54
52
|
},
|
|
55
53
|
/**
|
|
56
54
|
* Finds a single document matching the filter.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { FieldPath, PathValue } from "./paths";
|
|
2
|
+
export declare const allowedOperators: readonly ["$eq", "$ne", "$in", "$nin", "$exists", "$gt", "$gte", "$lt", "$lte", "$regex", "$and", "$or", "$nor", "$not"];
|
|
3
|
+
export type AllowedFilterOperator = (typeof allowedOperators)[number];
|
|
4
|
+
type ComparisonOperators<T> = [NonNullable<T>] extends [never] ? {} : [NonNullable<T>] extends [string | number | Date] ? {
|
|
5
|
+
$gt?: NonNullable<T>;
|
|
6
|
+
$gte?: NonNullable<T>;
|
|
7
|
+
$lt?: NonNullable<T>;
|
|
8
|
+
$lte?: NonNullable<T>;
|
|
9
|
+
} : {};
|
|
10
|
+
type RegexOperator<T> = [NonNullable<T>] extends [never] ? {} : [NonNullable<T>] extends [string] ? {
|
|
11
|
+
$regex?: RegExp;
|
|
12
|
+
} : {};
|
|
13
|
+
export type FilterOperators<T> = {
|
|
14
|
+
$eq?: T;
|
|
15
|
+
$ne?: T;
|
|
16
|
+
$in?: T[];
|
|
17
|
+
$nin?: T[];
|
|
18
|
+
$exists?: boolean;
|
|
19
|
+
$not?: FilterOperators<T>;
|
|
20
|
+
} & ComparisonOperators<T> & RegexOperator<T>;
|
|
21
|
+
/** A MongoDB filter over the known fields of a document. */
|
|
22
|
+
export type TypedFilter<T> = {
|
|
23
|
+
[Path in FieldPath<T>]?: PathValue<T, Path> | FilterOperators<PathValue<T, Path>>;
|
|
24
|
+
} & {
|
|
25
|
+
$or?: TypedFilter<T>[];
|
|
26
|
+
$and?: TypedFilter<T>[];
|
|
27
|
+
$nor?: TypedFilter<T>[];
|
|
28
|
+
};
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Shared limit for TypeScript recursion and runtime schema traversal. */
|
|
2
|
+
export declare const MAX_FIELD_PATH_DEPTH = 8;
|
|
3
|
+
type AtomicValue = Date | RegExp | Uint8Array | ReadonlyMap<unknown, unknown> | ReadonlySet<unknown> | readonly unknown[] | {
|
|
4
|
+
readonly _bsontype: string;
|
|
5
|
+
};
|
|
6
|
+
type FieldName<Key extends string> = Key extends "" | `$${string}` | `${string}.${string}` | `${string}\0${string}` ? never : Key;
|
|
7
|
+
type IsUnion<T, Whole = T> = T extends Whole ? [Whole] extends [T] ? false : true : never;
|
|
8
|
+
type ObjectPaths<T, Depth extends unknown[] = [], TraverseUnions extends boolean = true> = 0 extends 1 & T ? never : Depth["length"] extends typeof MAX_FIELD_PATH_DEPTH ? never : TraverseUnions extends false ? true extends IsUnion<NonNullable<T>> ? never : ObjectFieldPaths<T, Depth, TraverseUnions> : ObjectFieldPaths<T, Depth, TraverseUnions>;
|
|
9
|
+
type ObjectFieldPaths<T, Depth extends unknown[], TraverseUnions extends boolean> = T extends AtomicValue ? never : T extends object ? string extends keyof T ? never : {
|
|
10
|
+
[Key in Extract<keyof T, string>]-?: FieldName<Key> extends never ? never : Key | `${Key}.${ObjectPaths<T[Key], [...Depth, unknown], TraverseUnions>}`;
|
|
11
|
+
}[Extract<keyof T, string>] : never;
|
|
12
|
+
/** Known object fields, including dotted paths up to eight segments deep. */
|
|
13
|
+
export type FieldPath<T> = ObjectPaths<T>;
|
|
14
|
+
/** Update paths treat union-valued fields as atomic to preserve variant invariants. */
|
|
15
|
+
export type UpdateFieldPath<T> = ObjectPaths<T, [], false>;
|
|
16
|
+
/** The value at a path; optional/nullable ancestors do not change the leaf type. */
|
|
17
|
+
export type PathValue<T, Path extends string> = T extends null | undefined ? never : Path extends `${infer Head}.${infer Tail}` ? Head extends keyof T ? PathValue<T[Head], Tail> : never : Path extends keyof T ? T[Path] : never;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { PathValue, UpdateFieldPath } from "./paths";
|
|
2
|
+
export declare const updateOperators: readonly ["$set", "$unset", "$inc", "$min", "$max", "$setOnInsert"];
|
|
3
|
+
export type UpdateOperator = (typeof updateOperators)[number];
|
|
4
|
+
type MutablePath<T> = Exclude<UpdateFieldPath<T>, "_id" | `_id.${string}`>;
|
|
5
|
+
type StoredValue<T, Path extends string> = Exclude<PathValue<T, Path>, undefined>;
|
|
6
|
+
type PathsOfType<T, Value> = {
|
|
7
|
+
[Path in MutablePath<T>]: 0 extends 1 & StoredValue<T, Path> ? never : [StoredValue<T, Path>] extends [never] ? never : [StoredValue<T, Path>] extends [Value] ? Path : never;
|
|
8
|
+
}[MutablePath<T>];
|
|
9
|
+
type OptionalPath<T> = {
|
|
10
|
+
[Path in MutablePath<T>]: undefined extends PathValue<T, Path> ? Path : never;
|
|
11
|
+
}[MutablePath<T>];
|
|
12
|
+
type FieldValues<T, Paths extends string> = [Paths] extends [never] ? Record<string, never> : {
|
|
13
|
+
[Path in Paths]?: StoredValue<T, Path>;
|
|
14
|
+
};
|
|
15
|
+
type FieldOperands<Paths extends string, Operand> = [Paths] extends [never] ? Record<string, never> : {
|
|
16
|
+
[Path in Paths]?: Operand;
|
|
17
|
+
};
|
|
18
|
+
/** Typed atomic updates over known fields; _id is writable only on insertion. */
|
|
19
|
+
export type SafeUpdate<T> = {
|
|
20
|
+
$set?: FieldValues<T, MutablePath<T>>;
|
|
21
|
+
$setOnInsert?: FieldValues<T, UpdateFieldPath<T>>;
|
|
22
|
+
$unset?: FieldOperands<OptionalPath<T>, "" | 1 | true>;
|
|
23
|
+
$inc?: FieldOperands<PathsOfType<T, number>, number>;
|
|
24
|
+
$min?: FieldValues<T, PathsOfType<T, string | number | Date>>;
|
|
25
|
+
$max?: FieldValues<T, PathsOfType<T, string | number | Date>>;
|
|
26
|
+
};
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { ZodIssue } from "zod";
|
|
2
|
+
import type { AllowedFilterOperator } from "../types/filter";
|
|
3
|
+
export { createFilterSchema } from "../validation/filter-schema";
|
|
4
|
+
export declare function formatZodErrors(issues: ZodIssue[]): string;
|
|
5
|
+
export declare function isAllowedOperator(key: string): key is AllowedFilterOperator;
|
package/dist/util/helper.js
CHANGED
|
@@ -1,46 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createFilterSchema = void 0;
|
|
6
4
|
exports.formatZodErrors = formatZodErrors;
|
|
7
|
-
exports.createFilterSchema = createFilterSchema;
|
|
8
5
|
exports.isAllowedOperator = isAllowedOperator;
|
|
9
|
-
const
|
|
10
|
-
|
|
6
|
+
const filter_1 = require("../types/filter");
|
|
7
|
+
var filter_schema_1 = require("../validation/filter-schema");
|
|
8
|
+
Object.defineProperty(exports, "createFilterSchema", { enumerable: true, get: function () { return filter_schema_1.createFilterSchema; } });
|
|
11
9
|
function formatZodErrors(issues) {
|
|
12
10
|
return issues
|
|
13
11
|
.map(issue => `Error at field - ${issue.path.join(".")}: ${issue.message}`)
|
|
14
12
|
.join("\n");
|
|
15
13
|
}
|
|
16
|
-
const comparisonOperators = (type) => zod_1.default
|
|
17
|
-
.object({
|
|
18
|
-
$eq: type.optional(),
|
|
19
|
-
$ne: type.optional(),
|
|
20
|
-
$gt: type.optional(),
|
|
21
|
-
$gte: type.optional(),
|
|
22
|
-
$lt: type.optional(),
|
|
23
|
-
$lte: type.optional(),
|
|
24
|
-
$in: zod_1.default.array(type).optional(),
|
|
25
|
-
$nin: zod_1.default.array(type).optional(),
|
|
26
|
-
$regex: zod_1.default.instanceof(RegExp).optional()
|
|
27
|
-
})
|
|
28
|
-
.optional();
|
|
29
|
-
function wrapWithOperators(type) {
|
|
30
|
-
return zod_1.default.union([type, comparisonOperators(type)]);
|
|
31
|
-
}
|
|
32
|
-
function createFilterSchema(schema) {
|
|
33
|
-
const shape = schema.shape;
|
|
34
|
-
const newShape = {};
|
|
35
|
-
for (const key in shape) {
|
|
36
|
-
newShape[key] = wrapWithOperators(shape[key]);
|
|
37
|
-
}
|
|
38
|
-
// lazy mora biti unutar rekursivnih poziva
|
|
39
|
-
const filterSchema = zod_1.default.lazy(() => zod_1.default
|
|
40
|
-
.object(Object.assign(Object.assign({}, newShape), { $or: zod_1.default.array(zod_1.default.lazy(() => filterSchema)).optional(), $and: zod_1.default.array(zod_1.default.lazy(() => filterSchema)).optional(), $not: zod_1.default.lazy(() => filterSchema).optional() }))
|
|
41
|
-
.strict());
|
|
42
|
-
return filterSchema;
|
|
43
|
-
}
|
|
44
14
|
function isAllowedOperator(key) {
|
|
45
|
-
return
|
|
15
|
+
return filter_1.allowedOperators.includes(key);
|
|
46
16
|
}
|
package/dist/util/types.js
CHANGED
|
@@ -1,19 +1,5 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.allowedOperators = void 0;
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
"$gte",
|
|
7
|
-
"$lt",
|
|
8
|
-
"$lte",
|
|
9
|
-
"$in",
|
|
10
|
-
"$nin",
|
|
11
|
-
"$ne",
|
|
12
|
-
"$eq",
|
|
13
|
-
"$exists",
|
|
14
|
-
"$regex",
|
|
15
|
-
"$and",
|
|
16
|
-
"$or",
|
|
17
|
-
"$not",
|
|
18
|
-
"$nor"
|
|
19
|
-
];
|
|
4
|
+
var filter_1 = require("../types/filter");
|
|
5
|
+
Object.defineProperty(exports, "allowedOperators", { enumerable: true, get: function () { return filter_1.allowedOperators; } });
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { ZodObject, ZodRawShape, ZodSchema } from "zod";
|
|
2
|
+
export { validateUpdate } from "../validation/update";
|
|
3
|
+
export declare function validateOrThrow<T>(schema: ZodSchema<T>, data: unknown): T;
|
|
4
|
+
export declare function validateFilterOperators(filter: unknown): void;
|
|
5
|
+
export declare function validateFilter<T extends ZodObject<ZodRawShape>>(filter: unknown, schema: T): unknown;
|
package/dist/util/validate.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateUpdate = void 0;
|
|
3
4
|
exports.validateOrThrow = validateOrThrow;
|
|
4
5
|
exports.validateFilterOperators = validateFilterOperators;
|
|
5
6
|
exports.validateFilter = validateFilter;
|
|
6
|
-
exports.validateUpdate = validateUpdate;
|
|
7
7
|
const zod_1 = require("zod");
|
|
8
8
|
const helper_1 = require("./helper");
|
|
9
|
+
var update_1 = require("../validation/update");
|
|
10
|
+
Object.defineProperty(exports, "validateUpdate", { enumerable: true, get: function () { return update_1.validateUpdate; } });
|
|
9
11
|
function validateOrThrow(schema, data) {
|
|
10
12
|
try {
|
|
11
13
|
return schema.parse(data);
|
|
@@ -21,22 +23,18 @@ function validateOrThrow(schema, data) {
|
|
|
21
23
|
function validateFilterOperators(filter) {
|
|
22
24
|
if (!filter || typeof filter !== "object")
|
|
23
25
|
return;
|
|
24
|
-
for (const key
|
|
26
|
+
for (const [key, value] of Object.entries(filter)) {
|
|
25
27
|
if (key.startsWith("$")) {
|
|
26
28
|
if (!(0, helper_1.isAllowedOperator)(key)) {
|
|
27
29
|
throw new Error(`Invalid filter operator: ${key}`);
|
|
28
30
|
}
|
|
29
31
|
}
|
|
30
|
-
const value = filter[key];
|
|
31
32
|
if (typeof value === "object" && value !== null) {
|
|
32
|
-
|
|
33
|
+
validateFilterOperators(value);
|
|
33
34
|
}
|
|
34
35
|
}
|
|
35
36
|
}
|
|
36
37
|
function validateFilter(filter, schema) {
|
|
37
|
-
if (!filter || typeof filter !== "object")
|
|
38
|
-
return;
|
|
39
|
-
validateFilterOperators(filter);
|
|
40
38
|
const filterSchema = (0, helper_1.createFilterSchema)(schema);
|
|
41
39
|
const parsed = filterSchema.safeParse(filter);
|
|
42
40
|
if (!parsed.success) {
|
|
@@ -44,47 +42,3 @@ function validateFilter(filter, schema) {
|
|
|
44
42
|
}
|
|
45
43
|
return filter;
|
|
46
44
|
}
|
|
47
|
-
function validateUpdate(update, schema) {
|
|
48
|
-
if (!update || typeof update !== "object")
|
|
49
|
-
return;
|
|
50
|
-
const shape = schema.shape;
|
|
51
|
-
if (update.$set) {
|
|
52
|
-
const result = schema.partial().safeParse(update.$set);
|
|
53
|
-
if (!result.success) {
|
|
54
|
-
throw new Error(`Invalid $set update: ${result.error.message}`);
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
if (update.$setOnInsert) {
|
|
58
|
-
const result = schema.partial().safeParse(update.$setOnInsert);
|
|
59
|
-
if (!result.success) {
|
|
60
|
-
throw new Error(`Invalid $setOnInsert update: ${result.error.message}`);
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
if (update.$unset) {
|
|
64
|
-
const keys = Object.keys(update.$unset);
|
|
65
|
-
const allowed = Object.keys(shape);
|
|
66
|
-
for (const key of keys) {
|
|
67
|
-
if (!allowed.includes(key)) {
|
|
68
|
-
throw new Error(`Invalid $unset key: ${key}`);
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
for (const op of ["$inc", "$min", "$max"]) {
|
|
73
|
-
if (update[op]) {
|
|
74
|
-
for (const key in update[op]) {
|
|
75
|
-
const field = shape[key];
|
|
76
|
-
if (!field) {
|
|
77
|
-
throw new Error(`Invalid $inc key: ${key}, field not found in schema`);
|
|
78
|
-
}
|
|
79
|
-
let base = field;
|
|
80
|
-
while (base._def.typeName === "ZodOptional" ||
|
|
81
|
-
base._def.typeName === "ZodNullable") {
|
|
82
|
-
base = base._def.innerType;
|
|
83
|
-
}
|
|
84
|
-
if (base._def.typeName !== "ZodNumber") {
|
|
85
|
-
throw new Error(`Invalid $inc key: ${key}, not a number field`);
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.createFilterSchema = createFilterSchema;
|
|
4
|
+
const zod_1 = require("zod");
|
|
5
|
+
const schema_paths_1 = require("./schema-paths");
|
|
6
|
+
const schema_types_1 = require("./schema-types");
|
|
7
|
+
const filterSchemas = new WeakMap();
|
|
8
|
+
function createFieldCondition(field) {
|
|
9
|
+
const shape = {
|
|
10
|
+
$eq: field.optional(),
|
|
11
|
+
$ne: field.optional(),
|
|
12
|
+
$in: zod_1.z.array(field).optional(),
|
|
13
|
+
$nin: zod_1.z.array(field).optional(),
|
|
14
|
+
$exists: zod_1.z.boolean().optional()
|
|
15
|
+
};
|
|
16
|
+
if ((0, schema_types_1.everySchemaVariant)(field, schema_types_1.isComparableSchema)) {
|
|
17
|
+
const comparison = (0, schema_paths_1.unwrapSchema)(field).refine(value => value != null, "Expected a comparison value");
|
|
18
|
+
for (const operator of ["$gt", "$gte", "$lt", "$lte"])
|
|
19
|
+
shape[operator] = comparison.optional();
|
|
20
|
+
}
|
|
21
|
+
if ((0, schema_types_1.everySchemaVariant)(field, schema_types_1.isStringSchema))
|
|
22
|
+
shape.$regex = zod_1.z.instanceof(RegExp).optional();
|
|
23
|
+
const operators = zod_1.z.object(Object.assign(Object.assign({}, shape), { $not: zod_1.z.lazy(() => operators).optional() })).strict().refine(value => Object.keys(value).length > 0, "Expected a filter operator");
|
|
24
|
+
return zod_1.z.unknown().superRefine((value, context) => {
|
|
25
|
+
// An operator document must never fall back to a permissive object schema.
|
|
26
|
+
const isOperator = value !== null && typeof value === "object" && !Array.isArray(value) &&
|
|
27
|
+
Object.keys(value).some(key => key.startsWith("$"));
|
|
28
|
+
const result = (isOperator ? operators : field).safeParse(value);
|
|
29
|
+
if (!result.success) {
|
|
30
|
+
for (const issue of result.error.issues)
|
|
31
|
+
context.addIssue(issue);
|
|
32
|
+
}
|
|
33
|
+
}).optional();
|
|
34
|
+
}
|
|
35
|
+
/** Compile once per immutable Zod schema and reuse across collection operations. */
|
|
36
|
+
function createFilterSchema(schema) {
|
|
37
|
+
const cached = filterSchemas.get(schema);
|
|
38
|
+
if (cached)
|
|
39
|
+
return cached;
|
|
40
|
+
const shape = Object.create(null);
|
|
41
|
+
for (const [path, field] of (0, schema_paths_1.collectFieldSchemas)(schema))
|
|
42
|
+
shape[path] = createFieldCondition(field);
|
|
43
|
+
const recursiveFilter = zod_1.z.lazy(() => filter);
|
|
44
|
+
const filter = zod_1.z.object(Object.assign(Object.assign({}, shape), { $or: zod_1.z.array(recursiveFilter).nonempty().optional(), $and: zod_1.z.array(recursiveFilter).nonempty().optional(), $nor: zod_1.z.array(recursiveFilter).nonempty().optional() })).strict();
|
|
45
|
+
filterSchemas.set(schema, filter);
|
|
46
|
+
return filter;
|
|
47
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** Unwrap containers without traversing arrays or opaque/custom values. */
|
|
3
|
+
export declare function unwrapSchema(schema: z.ZodTypeAny, { preserveNullable }?: {
|
|
4
|
+
preserveNullable?: boolean | undefined;
|
|
5
|
+
}): z.ZodTypeAny;
|
|
6
|
+
/** Enumerate the same finite object paths exposed by FieldPath<T>. */
|
|
7
|
+
export declare function collectFieldSchemas(schema: z.AnyZodObject, { traverseUnions }?: {
|
|
8
|
+
traverseUnions?: boolean | undefined;
|
|
9
|
+
}): ReadonlyMap<string, z.ZodTypeAny>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.unwrapSchema = unwrapSchema;
|
|
4
|
+
exports.collectFieldSchemas = collectFieldSchemas;
|
|
5
|
+
const zod_1 = require("zod");
|
|
6
|
+
const paths_1 = require("../types/paths");
|
|
7
|
+
/** Unwrap containers without traversing arrays or opaque/custom values. */
|
|
8
|
+
function unwrapSchema(schema, { preserveNullable = false } = {}) {
|
|
9
|
+
const visited = new Set();
|
|
10
|
+
while (!visited.has(schema)) {
|
|
11
|
+
visited.add(schema);
|
|
12
|
+
if (schema instanceof zod_1.z.ZodOptional || (!preserveNullable && schema instanceof zod_1.z.ZodNullable) ||
|
|
13
|
+
schema instanceof zod_1.z.ZodBranded || schema instanceof zod_1.z.ZodReadonly) {
|
|
14
|
+
schema = schema.unwrap();
|
|
15
|
+
}
|
|
16
|
+
else if (schema instanceof zod_1.z.ZodDefault) {
|
|
17
|
+
schema = schema.removeDefault();
|
|
18
|
+
}
|
|
19
|
+
else if (schema instanceof zod_1.z.ZodCatch) {
|
|
20
|
+
schema = schema.removeCatch();
|
|
21
|
+
}
|
|
22
|
+
else if (schema instanceof zod_1.z.ZodLazy) {
|
|
23
|
+
schema = schema.schema;
|
|
24
|
+
}
|
|
25
|
+
else if (schema instanceof zod_1.z.ZodEffects && schema._def.effect.type === "refinement") {
|
|
26
|
+
// Refinements preserve the shape; transforms may produce a different object.
|
|
27
|
+
schema = schema.innerType();
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
break;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return schema;
|
|
34
|
+
}
|
|
35
|
+
function isFieldName(key) {
|
|
36
|
+
return key.length > 0 && !key.startsWith("$") && !key.includes(".") && !key.includes("\0");
|
|
37
|
+
}
|
|
38
|
+
/** Enumerate the same finite object paths exposed by FieldPath<T>. */
|
|
39
|
+
function collectFieldSchemas(schema, { traverseUnions = true } = {}) {
|
|
40
|
+
const fields = new Map();
|
|
41
|
+
function visit(current, prefix, depth, ancestors = new Set()) {
|
|
42
|
+
if (depth >= paths_1.MAX_FIELD_PATH_DEPTH)
|
|
43
|
+
return;
|
|
44
|
+
const base = unwrapSchema(current);
|
|
45
|
+
if (ancestors.has(base))
|
|
46
|
+
return;
|
|
47
|
+
const nextAncestors = new Set(ancestors).add(base);
|
|
48
|
+
if (base instanceof zod_1.z.ZodUnion || base instanceof zod_1.z.ZodDiscriminatedUnion) {
|
|
49
|
+
if (!traverseUnions)
|
|
50
|
+
return;
|
|
51
|
+
for (const option of base.options)
|
|
52
|
+
visit(option, prefix, depth, nextAncestors);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (!(base instanceof zod_1.z.ZodObject))
|
|
56
|
+
return;
|
|
57
|
+
for (const [key, field] of Object.entries(base.shape)) {
|
|
58
|
+
if (!isFieldName(key))
|
|
59
|
+
continue;
|
|
60
|
+
const path = prefix ? `${prefix}.${key}` : key;
|
|
61
|
+
const existing = fields.get(path);
|
|
62
|
+
fields.set(path, existing ? zod_1.z.union([existing, field]) : field);
|
|
63
|
+
// Reset ancestry at each field: recursive objects are bounded by path depth.
|
|
64
|
+
visit(field, path, depth + 1);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
visit(schema, "", 0);
|
|
68
|
+
return fields;
|
|
69
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/** Check all value variants, with nullable comparisons allowed only for filters. */
|
|
3
|
+
export declare function everySchemaVariant(schema: z.ZodTypeAny, predicate: (schema: z.ZodTypeAny) => boolean, { ignoreNullable }?: {
|
|
4
|
+
ignoreNullable?: boolean | undefined;
|
|
5
|
+
}, ancestors?: Set<z.ZodTypeAny>): boolean;
|
|
6
|
+
export declare function isStringSchema(schema: z.ZodTypeAny): boolean;
|
|
7
|
+
export declare function isNumericSchema(schema: z.ZodTypeAny): boolean;
|
|
8
|
+
export declare function isComparableSchema(schema: z.ZodTypeAny): boolean;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.everySchemaVariant = everySchemaVariant;
|
|
4
|
+
exports.isStringSchema = isStringSchema;
|
|
5
|
+
exports.isNumericSchema = isNumericSchema;
|
|
6
|
+
exports.isComparableSchema = isComparableSchema;
|
|
7
|
+
const zod_1 = require("zod");
|
|
8
|
+
const schema_paths_1 = require("./schema-paths");
|
|
9
|
+
/** Check all value variants, with nullable comparisons allowed only for filters. */
|
|
10
|
+
function everySchemaVariant(schema, predicate, { ignoreNullable = true } = {}, ancestors = new Set()) {
|
|
11
|
+
const base = (0, schema_paths_1.unwrapSchema)(schema, { preserveNullable: !ignoreNullable });
|
|
12
|
+
if (ancestors.has(base))
|
|
13
|
+
return false;
|
|
14
|
+
if (base instanceof zod_1.z.ZodUnion || base instanceof zod_1.z.ZodDiscriminatedUnion) {
|
|
15
|
+
const next = new Set(ancestors).add(base);
|
|
16
|
+
const options = base.options.filter(option => !(option instanceof zod_1.z.ZodUndefined) && !(ignoreNullable && option instanceof zod_1.z.ZodNull));
|
|
17
|
+
return options.length > 0 && options.every(option => everySchemaVariant(option, predicate, { ignoreNullable }, next));
|
|
18
|
+
}
|
|
19
|
+
return predicate(base);
|
|
20
|
+
}
|
|
21
|
+
function enumValues(schema) {
|
|
22
|
+
// Numeric TypeScript enums also contain reverse mappings; keep actual values.
|
|
23
|
+
return Object.values(schema.enum).filter(value => schema.safeParse(value).success);
|
|
24
|
+
}
|
|
25
|
+
function isStringSchema(schema) {
|
|
26
|
+
if (schema instanceof zod_1.z.ZodString || schema instanceof zod_1.z.ZodEnum)
|
|
27
|
+
return true;
|
|
28
|
+
if (schema instanceof zod_1.z.ZodLiteral)
|
|
29
|
+
return typeof schema.value === "string";
|
|
30
|
+
if (schema instanceof zod_1.z.ZodNativeEnum) {
|
|
31
|
+
const values = enumValues(schema);
|
|
32
|
+
return values.length > 0 && values.every(value => typeof value === "string");
|
|
33
|
+
}
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
function isNumericSchema(schema) {
|
|
37
|
+
if (schema instanceof zod_1.z.ZodNumber)
|
|
38
|
+
return true;
|
|
39
|
+
if (schema instanceof zod_1.z.ZodLiteral)
|
|
40
|
+
return typeof schema.value === "number";
|
|
41
|
+
if (schema instanceof zod_1.z.ZodNativeEnum) {
|
|
42
|
+
const values = enumValues(schema);
|
|
43
|
+
return values.length > 0 && values.every(value => typeof value === "number");
|
|
44
|
+
}
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
function isComparableSchema(schema) {
|
|
48
|
+
if (isStringSchema(schema) || isNumericSchema(schema) || schema instanceof zod_1.z.ZodDate)
|
|
49
|
+
return true;
|
|
50
|
+
if (schema instanceof zod_1.z.ZodNativeEnum) {
|
|
51
|
+
const values = enumValues(schema);
|
|
52
|
+
return values.length > 0 && values.every(value => typeof value === "string" || typeof value === "number");
|
|
53
|
+
}
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
export interface UpdateField {
|
|
3
|
+
readonly schema: z.ZodTypeAny;
|
|
4
|
+
readonly optional: boolean;
|
|
5
|
+
readonly numeric: boolean;
|
|
6
|
+
readonly comparable: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** Reuse path metadata without weakening unions into independently writable fields. */
|
|
9
|
+
export declare function getUpdateFields(schema: z.AnyZodObject): ReadonlyMap<string, UpdateField>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getUpdateFields = getUpdateFields;
|
|
4
|
+
const zod_1 = require("zod");
|
|
5
|
+
const schema_paths_1 = require("./schema-paths");
|
|
6
|
+
const schema_types_1 = require("./schema-types");
|
|
7
|
+
const fieldsBySchema = new WeakMap();
|
|
8
|
+
function canOmit(schema, ancestors = new Set()) {
|
|
9
|
+
if (ancestors.has(schema))
|
|
10
|
+
return false;
|
|
11
|
+
const next = new Set(ancestors).add(schema);
|
|
12
|
+
// A default fills undefined on parsing, but the stored output field is required.
|
|
13
|
+
if (schema instanceof zod_1.z.ZodDefault)
|
|
14
|
+
return false;
|
|
15
|
+
if (schema instanceof zod_1.z.ZodOptional || schema instanceof zod_1.z.ZodUndefined ||
|
|
16
|
+
schema instanceof zod_1.z.ZodVoid || schema instanceof zod_1.z.ZodAny || schema instanceof zod_1.z.ZodUnknown)
|
|
17
|
+
return true;
|
|
18
|
+
if (schema instanceof zod_1.z.ZodNullable || schema instanceof zod_1.z.ZodBranded || schema instanceof zod_1.z.ZodReadonly) {
|
|
19
|
+
return canOmit(schema.unwrap(), next);
|
|
20
|
+
}
|
|
21
|
+
if (schema instanceof zod_1.z.ZodCatch)
|
|
22
|
+
return canOmit(schema.removeCatch(), next);
|
|
23
|
+
if (schema instanceof zod_1.z.ZodLazy)
|
|
24
|
+
return canOmit(schema.schema, next);
|
|
25
|
+
if (schema instanceof zod_1.z.ZodEffects && schema._def.effect.type === "refinement") {
|
|
26
|
+
return canOmit(schema.innerType(), next);
|
|
27
|
+
}
|
|
28
|
+
if (schema instanceof zod_1.z.ZodUnion) {
|
|
29
|
+
return schema.options.some(option => canOmit(option, next));
|
|
30
|
+
}
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
/** Reuse path metadata without weakening unions into independently writable fields. */
|
|
34
|
+
function getUpdateFields(schema) {
|
|
35
|
+
const cached = fieldsBySchema.get(schema);
|
|
36
|
+
if (cached)
|
|
37
|
+
return cached;
|
|
38
|
+
const fields = new Map();
|
|
39
|
+
for (const [path, field] of (0, schema_paths_1.collectFieldSchemas)(schema, { traverseUnions: false })) {
|
|
40
|
+
fields.set(path, {
|
|
41
|
+
schema: field,
|
|
42
|
+
optional: canOmit(field),
|
|
43
|
+
numeric: (0, schema_types_1.everySchemaVariant)(field, schema_types_1.isNumericSchema, { ignoreNullable: false }),
|
|
44
|
+
comparable: (0, schema_types_1.everySchemaVariant)(field, schema_types_1.isComparableSchema, { ignoreNullable: false })
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
fieldsBySchema.set(schema, fields);
|
|
48
|
+
return fields;
|
|
49
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { AnyZodObject, TypeOf } from "zod";
|
|
2
|
+
import type { SafeUpdate } from "../types/update";
|
|
3
|
+
/** Validate and normalize an atomic update without mutating the caller's object. */
|
|
4
|
+
export declare function validateUpdate<TSchema extends AnyZodObject>(update: unknown, schema: TSchema): SafeUpdate<TypeOf<TSchema>>;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateUpdate = validateUpdate;
|
|
4
|
+
const update_1 = require("../types/update");
|
|
5
|
+
const update_fields_1 = require("./update-fields");
|
|
6
|
+
function isRecord(value) {
|
|
7
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
8
|
+
return false;
|
|
9
|
+
const prototype = Object.getPrototypeOf(value);
|
|
10
|
+
return prototype === Object.prototype || prototype === null;
|
|
11
|
+
}
|
|
12
|
+
function fail(operator, path, reason) {
|
|
13
|
+
throw new Error(`Invalid ${operator} update at "${path}": ${reason}`);
|
|
14
|
+
}
|
|
15
|
+
function validateOperand(operator, path, value, field) {
|
|
16
|
+
if (operator === "$unset") {
|
|
17
|
+
if (!field.optional)
|
|
18
|
+
fail(operator, path, "required fields cannot be removed");
|
|
19
|
+
if (value !== "" && value !== 1 && value !== true)
|
|
20
|
+
fail(operator, path, 'expected "", 1 or true');
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
if (value === undefined)
|
|
24
|
+
fail(operator, path, "undefined is not a stored value; use $unset for optional fields");
|
|
25
|
+
if (operator === "$inc") {
|
|
26
|
+
if (!field.numeric)
|
|
27
|
+
fail(operator, path, "expected a non-nullable numeric field");
|
|
28
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
29
|
+
fail(operator, path, "expected a finite number");
|
|
30
|
+
// The operand is a delta, not a replacement value subject to the field's range.
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
if ((operator === "$min" || operator === "$max") && !field.comparable) {
|
|
34
|
+
fail(operator, path, "expected a non-nullable string, number or date field");
|
|
35
|
+
}
|
|
36
|
+
const parsed = field.schema.safeParse(value);
|
|
37
|
+
if (!parsed.success)
|
|
38
|
+
fail(operator, path, parsed.error.message);
|
|
39
|
+
if (parsed.data === undefined)
|
|
40
|
+
fail(operator, path, "schema produced undefined; use $unset instead");
|
|
41
|
+
return parsed.data;
|
|
42
|
+
}
|
|
43
|
+
function validateConflicts(paths) {
|
|
44
|
+
const seen = new Set();
|
|
45
|
+
for (const path of paths) {
|
|
46
|
+
if (seen.has(path))
|
|
47
|
+
throw new Error(`Invalid update: conflicting operations on "${path}"`);
|
|
48
|
+
seen.add(path);
|
|
49
|
+
}
|
|
50
|
+
for (const path of paths) {
|
|
51
|
+
const segments = path.split(".");
|
|
52
|
+
for (let depth = 1; depth < segments.length; depth++) {
|
|
53
|
+
const ancestor = segments.slice(0, depth).join(".");
|
|
54
|
+
if (seen.has(ancestor))
|
|
55
|
+
throw new Error(`Invalid update: conflicting paths "${ancestor}" and "${path}"`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Validate and normalize an atomic update without mutating the caller's object. */
|
|
60
|
+
function validateUpdate(update, schema) {
|
|
61
|
+
if (!isRecord(update) || Object.keys(update).length === 0) {
|
|
62
|
+
throw new Error("Invalid update: expected a nonempty operator document");
|
|
63
|
+
}
|
|
64
|
+
const fields = (0, update_fields_1.getUpdateFields)(schema);
|
|
65
|
+
const normalized = Object.create(null);
|
|
66
|
+
const paths = [];
|
|
67
|
+
for (const [name, payload] of Object.entries(update)) {
|
|
68
|
+
if (!update_1.updateOperators.includes(name))
|
|
69
|
+
throw new Error(`Invalid update operator: ${name}`);
|
|
70
|
+
if (!isRecord(payload))
|
|
71
|
+
throw new Error(`Invalid ${name} update: expected a field document`);
|
|
72
|
+
const operator = name;
|
|
73
|
+
const values = Object.create(null);
|
|
74
|
+
for (const [path, value] of Object.entries(payload)) {
|
|
75
|
+
const field = fields.get(path);
|
|
76
|
+
if (!field)
|
|
77
|
+
fail(operator, path, "unknown or unsupported field path");
|
|
78
|
+
if (operator !== "$setOnInsert" && (path === "_id" || path.startsWith("_id."))) {
|
|
79
|
+
fail(operator, path, "_id is immutable");
|
|
80
|
+
}
|
|
81
|
+
values[path] = validateOperand(operator, path, value, field);
|
|
82
|
+
paths.push(path);
|
|
83
|
+
}
|
|
84
|
+
normalized[operator] = values;
|
|
85
|
+
}
|
|
86
|
+
validateConflicts(paths);
|
|
87
|
+
// Every key and value has been checked against the schema at this boundary.
|
|
88
|
+
return normalized;
|
|
89
|
+
}
|
package/package.json
CHANGED
|
@@ -1,42 +1,49 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "mongo-type-safe",
|
|
3
|
-
"version": "
|
|
4
|
-
"main": "dist/index.js",
|
|
5
|
-
"types": "dist/index.d.ts",
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
|
|
10
|
-
"
|
|
11
|
-
"
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
"
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
|
|
27
|
-
"
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
"
|
|
33
|
-
},
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
"
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "mongo-type-safe",
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"main": "dist/index.js",
|
|
5
|
+
"types": "dist/index.d.ts",
|
|
6
|
+
"files": [
|
|
7
|
+
"dist",
|
|
8
|
+
"CHANGELOG.md"
|
|
9
|
+
],
|
|
10
|
+
"scripts": {
|
|
11
|
+
"test": "jest",
|
|
12
|
+
"build": "tsc",
|
|
13
|
+
"prepack": "npm run test:types && npm run build",
|
|
14
|
+
"test:types": "tsc --project tsconfig.type-tests.json",
|
|
15
|
+
"test:unit": "jest --runInBand --runTestsByPath __tests__/validateFunctions.test.ts __tests__/model.test.ts __tests__/nestedFilters.test.ts __tests__/schemaPaths.test.ts __tests__/nestedUpdates.test.ts"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"mongodb",
|
|
19
|
+
"typescript",
|
|
20
|
+
"zod",
|
|
21
|
+
"schema",
|
|
22
|
+
"safe",
|
|
23
|
+
"validation",
|
|
24
|
+
"runtime",
|
|
25
|
+
"type-safe"
|
|
26
|
+
],
|
|
27
|
+
"author": "Marko Scekic",
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"description": "Type-safe MongoDB wrapper with Zod validation at runtime and compile-time.",
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"mongodb": "^6.17.0",
|
|
32
|
+
"zod": "^3.25.75"
|
|
33
|
+
},
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "https://github.com/sceka/mongo-type-safe"
|
|
37
|
+
},
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/sceka/mongo-type-safe/issues"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@types/jest": "^30.0.0",
|
|
43
|
+
"@types/node": "^24.0.10",
|
|
44
|
+
"jest": "^30.0.5",
|
|
45
|
+
"ts-jest": "^29.4.0",
|
|
46
|
+
"ts-node": "^10.9.2",
|
|
47
|
+
"typescript": "^5.8.3"
|
|
48
|
+
}
|
|
49
|
+
}
|
|
Binary file
|