ts-patch-mongoose 4.0.2 → 4.1.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/README.md CHANGED
@@ -27,12 +27,12 @@ I need to track changes of mongoose models and save them as patch history (audit
27
27
 
28
28
  ```json
29
29
  {
30
- "node": "20.x || 22.x || 24.x",
30
+ "node": ">=20",
31
31
  "mongoose": ">=6.6.0 <10"
32
32
  }
33
33
  ```
34
34
 
35
- CI tests against mongoose `6.12.2`, `7.6.4`, `8.23.0`, and `9.4.1`.
35
+ CI tests on Node.js `22.x` and `24.x` against mongoose `6.12.2`, `7.6.4`, `8.23.0`, and `9.4.1`, and on `26.x` with the mongoose version the lockfile pins.
36
36
 
37
37
  ## Features
38
38
 
@@ -46,7 +46,7 @@ CI tests against mongoose `6.12.2`, `7.6.4`, `8.23.0`, and `9.4.1`.
46
46
 
47
47
  ## Installation
48
48
 
49
- `mongoose` is a peer dependency — install it alongside `ts-patch-mongoose`.
49
+ `mongoose` is a peer dependency: install it alongside `ts-patch-mongoose`.
50
50
 
51
51
  ```bash
52
52
  npm install ts-patch-mongoose mongoose
@@ -57,7 +57,7 @@ bun add ts-patch-mongoose mongoose
57
57
 
58
58
  ## Example
59
59
 
60
- Works with any Node.js framework — Express, Fastify, Koa, Hono, Nest, etc.
60
+ Works with any Node.js framework: Express, Fastify, Koa, Hono, Nest, etc.
61
61
  \
62
62
  How to use it with Express: [ts-express-tsx](https://github.com/ilovepixelart/ts-express-tsx)
63
63
 
@@ -156,7 +156,9 @@ BookSchema.plugin(patchHistoryPlugin, {
156
156
  await SomeOtherModel.deleteMany({ bookId: { $in: bookIds } })
157
157
  },
158
158
 
159
- // Custom error handler for history write failures (defaults to console.error)
159
+ // Custom error handler (defaults to console.error) for history write failures, and for getUser,
160
+ // getReason and getMetadata failures: those are reported once per operation, and the entry is
161
+ // still saved without that field
160
162
  onError: (error) => {
161
163
  console.error('Patch history error:', error)
162
164
  },
@@ -171,6 +173,12 @@ const Book = model('Book', BookSchema)
171
173
  export default Book
172
174
  ```
173
175
 
176
+ ## Transactions
177
+
178
+ Pass the session the usual way (`{ session }` in query options, `.session(session)`, `doc.save({ session })`, `create(docs, { session })`, `insertMany(docs, { session })`). The plugin reads the documents and reads and writes patch history in that session, so an aborted transaction leaves no history and changes to documents created earlier in the same transaction are recorded. With mongoose 8+ `transactionAsyncLocalStorage`, the session is picked up without passing it.
179
+
180
+ `insertMany(docs, { session, lean: true })` returns plain objects that do not carry the session, so their history is written outside the transaction.
181
+
174
182
  ## Subscribe
175
183
 
176
184
  You can subscribe to events using patchEventEmitter anywhere in your application `handlers/BookHandler.ts`
package/dist/index.cjs CHANGED
@@ -202,6 +202,7 @@ const cloneDeep = (value, seen = /* @__PURE__ */ new WeakMap()) => {
202
202
  }
203
203
  return cloneCollection(value, seen);
204
204
  };
205
+ const HISTORY_BATCH_SIZE = 1e3;
205
206
  const chunk = (array, size) => {
206
207
  const result = [];
207
208
  for (let i = 0; i < array.length; i += size) {
@@ -212,6 +213,7 @@ const chunk = (array, size) => {
212
213
  const isHookIgnored = (options) => {
213
214
  return options.ignoreHook === true || options.ignoreEvent === true && options.ignorePatchHistory === true;
214
215
  };
216
+ const sessionOptions = (session) => session ? { session } : {};
215
217
  const toObjectOptions = {
216
218
  depopulate: true,
217
219
  virtuals: false
@@ -406,8 +408,20 @@ const getMetadata = async (opts, doc) => getOptionalField(opts.getMetadata, doc)
406
408
  const getValue = (item) => {
407
409
  return item.status === "fulfilled" ? item.value : void 0;
408
410
  };
409
- const getData = async (opts, doc) => {
411
+ const reportedGetters = /* @__PURE__ */ new WeakMap();
412
+ const reportRejections = (opts, context, results) => {
413
+ const onError = opts.onError ?? console.error;
414
+ const reported = context ? reportedGetters.get(context) ?? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set();
415
+ if (context) reportedGetters.set(context, reported);
416
+ for (const [index, result] of results.entries()) {
417
+ if (result.status === "fulfilled" || reported.has(index)) continue;
418
+ reported.add(index);
419
+ onError(result.reason instanceof Error ? result.reason : new Error(String(result.reason)));
420
+ }
421
+ };
422
+ const getData = async (opts, doc, context) => {
410
423
  return Promise.allSettled([getUser(opts, doc), getReason(opts, doc), getMetadata(opts, doc)]).then(([user, reason, metadata]) => {
424
+ reportRejections(opts, context, [user, reason, metadata]);
411
425
  return [getValue(user), getValue(reason), getValue(metadata)];
412
426
  });
413
427
  };
@@ -425,14 +439,14 @@ const bulkPatch = async (opts, context, eventKey, docsKey) => {
425
439
  const docs = context[docsKey];
426
440
  const key = eventKey === "eventCreated" ? "doc" : "oldDoc";
427
441
  if (isEmpty(docs) || !docs || !event && !history) return;
428
- const chunks = chunk(docs, 1e3);
442
+ const chunks = chunk(docs, HISTORY_BATCH_SIZE);
429
443
  for (const batch of chunks) {
430
444
  const bulk = [];
431
445
  for (const doc of batch) {
432
446
  const omitted = getObjectOmit(opts, doc);
433
447
  emitEvent(context, event, { [key]: omitted });
434
448
  if (history) {
435
- const [user, reason, metadata] = await getData(opts, doc);
449
+ const [user, reason, metadata] = await getData(opts, doc, context);
436
450
  bulk.push({
437
451
  insertOne: {
438
452
  document: {
@@ -452,7 +466,7 @@ const bulkPatch = async (opts, context, eventKey, docsKey) => {
452
466
  }
453
467
  if (history && !isEmpty(bulk)) {
454
468
  const onError = opts.onError ?? console.error;
455
- await HistoryModel.bulkWrite(bulk, { ordered: false }).catch((error) => {
469
+ await HistoryModel.bulkWrite(bulk, { ordered: false, ...sessionOptions(context.session) }).catch((error) => {
456
470
  onError(error);
457
471
  });
458
472
  }
@@ -461,36 +475,68 @@ const bulkPatch = async (opts, context, eventKey, docsKey) => {
461
475
  const createPatch = async (opts, context) => {
462
476
  await bulkPatch(opts, context, "eventCreated", "createdDocs");
463
477
  };
464
- const updatePatch = async (opts, context, current, original) => {
465
- const history = isPatchHistoryEnabled(opts, context);
478
+ const diffAndEmit = (opts, context, current, original) => {
466
479
  const currentObject = getJsonOmit(opts, current);
467
480
  const originalObject = getJsonOmit(opts, original);
468
- if (isEmpty(originalObject) || isEmpty(currentObject)) return;
481
+ if (isEmpty(originalObject) || isEmpty(currentObject)) return void 0;
469
482
  const patch = compare(originalObject, currentObject, true);
470
- if (isEmpty(patch)) return;
483
+ if (isEmpty(patch)) return void 0;
471
484
  emitEvent(context, opts.eventUpdated, { oldDoc: original, doc: current, patch });
472
- if (history) {
473
- let version = 0;
474
- const lastHistory = await HistoryModel.findOne({ collectionId: original._id }).sort("-version").exec();
475
- if (lastHistory) {
476
- version = lastHistory.version + 1;
485
+ return patch;
486
+ };
487
+ const updateEntry = (context, original, patch, version, [user, reason, metadata]) => ({
488
+ op: context.op,
489
+ modelName: context.modelName,
490
+ collectionName: context.collectionName,
491
+ collectionId: original._id,
492
+ patch,
493
+ version,
494
+ ...user !== void 0 && { user },
495
+ ...reason !== void 0 && { reason },
496
+ ...metadata !== void 0 && { metadata }
497
+ });
498
+ const updatePatch = async (opts, context, current, original) => {
499
+ const patch = diffAndEmit(opts, context, current, original);
500
+ if (!patch || !isPatchHistoryEnabled(opts, context)) return;
501
+ let version = 0;
502
+ const lastHistory = await HistoryModel.findOne({ collectionId: original._id }, null, sessionOptions(context.session)).sort("-version").exec();
503
+ if (lastHistory) {
504
+ version = lastHistory.version + 1;
505
+ }
506
+ const data = await getData(opts, current, context);
507
+ const onError = opts.onError ?? console.error;
508
+ await HistoryModel.create([updateEntry(context, original, patch, version, data)], sessionOptions(context.session)).catch((error) => {
509
+ onError(error);
510
+ });
511
+ };
512
+ const nextVersions = async (ids, session) => {
513
+ const last = await HistoryModel.aggregate([{ $match: { collectionId: { $in: ids } } }, { $group: { _id: "$collectionId", version: { $max: "$version" } } }]).option(sessionOptions(session)).exec();
514
+ return new Map(last.map(({ _id, version }) => [String(_id), version + 1]));
515
+ };
516
+ const updatePatchBatch = async (opts, context, pairs) => {
517
+ const [first] = pairs;
518
+ if (pairs.length === 1 && first) {
519
+ await updatePatch(opts, context, first.current, first.original);
520
+ return;
521
+ }
522
+ const history = isPatchHistoryEnabled(opts, context);
523
+ const pending = [];
524
+ for (const { current, original } of pairs) {
525
+ const patch = diffAndEmit(opts, context, current, original);
526
+ if (patch && history) {
527
+ pending.push({ original, patch, data: await getData(opts, current, context) });
477
528
  }
478
- const [user, reason, metadata] = await getData(opts, current);
479
- const onError = opts.onError ?? console.error;
480
- await HistoryModel.create({
481
- op: context.op,
482
- modelName: context.modelName,
483
- collectionName: context.collectionName,
484
- collectionId: original._id,
485
- patch,
486
- version,
487
- ...user !== void 0 && { user },
488
- ...reason !== void 0 && { reason },
489
- ...metadata !== void 0 && { metadata }
490
- }).catch((error) => {
491
- onError(error);
492
- });
493
529
  }
530
+ if (isEmpty(pending)) return;
531
+ const versions = await nextVersions(
532
+ pending.map(({ original }) => original._id),
533
+ context.session
534
+ );
535
+ const entries = pending.map(({ original, patch, data }) => updateEntry(context, original, patch, versions.get(String(original._id)) ?? 0, data));
536
+ const onError = opts.onError ?? console.error;
537
+ await HistoryModel.insertMany(entries, { ordered: false, ...sessionOptions(context.session) }).catch((error) => {
538
+ onError(error);
539
+ });
494
540
  };
495
541
  const deletePatch = async (opts, context) => {
496
542
  await bulkPatch(opts, context, "eventDeleted", "deletedDocs");
@@ -508,15 +554,16 @@ const deleteHooksInitialize = (schema, opts) => {
508
554
  modelName: opts.modelName ?? model.modelName,
509
555
  collectionName: opts.collectionName ?? model.collection.collectionName,
510
556
  ignoreEvent: options.ignoreEvent,
511
- ignorePatchHistory: options.ignorePatchHistory
557
+ ignorePatchHistory: options.ignorePatchHistory,
558
+ session: options.session ?? null
512
559
  };
513
560
  if (["remove", "deleteMany"].includes(this._context.op) && !options.single) {
514
- const docs = await model.find(filter).lean().exec();
561
+ const docs = await model.find(filter, null, sessionOptions(options.session)).lean().exec();
515
562
  if (!isEmpty(docs)) {
516
563
  this._context.deletedDocs = docs;
517
564
  }
518
565
  } else {
519
- const doc = await model.findOne(filter).lean().exec();
566
+ const doc = await model.findOne(filter, null, sessionOptions(options.session)).lean().exec();
520
567
  if (!isEmpty(doc)) {
521
568
  this._context.deletedDocs = [doc];
522
569
  }
@@ -542,12 +589,13 @@ const saveHooksInitialize = (schema, opts) => {
542
589
  op: this.isNew ? "create" : "update",
543
590
  modelName: opts.modelName ?? model.modelName,
544
591
  collectionName: opts.collectionName ?? model.collection.collectionName,
545
- createdDocs: [current]
592
+ createdDocs: [current],
593
+ session: this.$session()
546
594
  };
547
595
  if (this.isNew) {
548
596
  await createPatch(opts, context);
549
597
  } else {
550
- const original = await model.findById(current._id).lean().exec();
598
+ const original = await model.findById(current._id, null, sessionOptions(context.session)).lean().exec();
551
599
  if (original) {
552
600
  await updatePatch(opts, context, current, original);
553
601
  }
@@ -784,17 +832,24 @@ const updateHooksInitialize = (schema, opts) => {
784
832
  op: this.op,
785
833
  modelName: opts.modelName ?? model.modelName,
786
834
  collectionName: opts.collectionName ?? model.collection.collectionName,
787
- isNew: Boolean(options.upsert) && await model.countDocuments(filter).exec() === 0,
835
+ isNew: Boolean(options.upsert) && await model.countDocuments(filter, sessionOptions(options.session)).exec() === 0,
788
836
  ignoreEvent: options.ignoreEvent,
789
- ignorePatchHistory: options.ignorePatchHistory
837
+ ignorePatchHistory: options.ignorePatchHistory,
838
+ session: options.session ?? null
790
839
  };
791
840
  const updateQuery = this.getUpdate();
792
841
  const { update, commands } = splitUpdateAndCommands(updateQuery);
793
- const cursor = model.find(filter).cursor();
794
- await cursor.eachAsync(async (doc) => {
795
- const origDoc = doc.toObject(toObjectOptions);
796
- await updatePatch(opts, this._context, assignUpdate(doc, update, commands), origDoc);
797
- });
842
+ const cursor = model.find(filter, null, sessionOptions(options.session)).cursor();
843
+ await cursor.eachAsync(
844
+ async (docs) => {
845
+ const pairs = docs.map((doc) => {
846
+ const original = doc.toObject(toObjectOptions);
847
+ return { current: assignUpdate(doc, update, commands), original };
848
+ });
849
+ await updatePatchBatch(opts, this._context, pairs);
850
+ },
851
+ { batchSize: HISTORY_BATCH_SIZE }
852
+ );
798
853
  });
799
854
  schema.post(updateMethods, { document: false, query: true }, async function() {
800
855
  const options = this.getOptions();
@@ -811,7 +866,7 @@ const updateHooksInitialize = (schema, opts) => {
811
866
  let current = null;
812
867
  for (const query of candidates) {
813
868
  if (current || isEmpty(query)) continue;
814
- const found = await model.findOne(query).sort({ _id: -1 }).lean().exec();
869
+ const found = await model.findOne(query, null, sessionOptions(this._context.session)).sort({ _id: -1 }).lean().exec();
815
870
  current = found;
816
871
  }
817
872
  if (current) {
@@ -839,7 +894,9 @@ const patchHistoryPlugin = (schema, opts) => {
839
894
  op: "create",
840
895
  modelName: opts.modelName ?? this.modelName,
841
896
  collectionName: opts.collectionName ?? this.collection.collectionName,
842
- createdDocs: docs
897
+ createdDocs: docs,
898
+ // insertMany sets the session of its options on every hydrated document; lean ones carry none
899
+ session: docs[0]?.$session?.() ?? null
843
900
  };
844
901
  await createPatch(opts, context);
845
902
  });
@@ -858,7 +915,8 @@ const patchHistoryPlugin = (schema, opts) => {
858
915
  op: "delete",
859
916
  modelName: opts.modelName ?? model.modelName,
860
917
  collectionName: opts.collectionName ?? model.collection.collectionName,
861
- deletedDocs: [original]
918
+ deletedDocs: [original],
919
+ session: this.$session()
862
920
  };
863
921
  await deletePatch(opts, context);
864
922
  });
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { Types, Query, HydratedDocument, Schema } from 'mongoose';
1
+ import { Types, Query, HydratedDocument, ClientSession, Schema } from 'mongoose';
2
2
  import EventEmitter from 'node:events';
3
3
 
4
4
  interface AddOperation<T> {
@@ -50,6 +50,7 @@ interface PatchContext<T> {
50
50
  deletedDocs?: HydratedDocument<T>[];
51
51
  ignoreEvent?: boolean;
52
52
  ignorePatchHistory?: boolean;
53
+ session?: ClientSession | null;
53
54
  }
54
55
  type HookContext<T> = Query<T, T> & {
55
56
  op: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","sources":["../src/json-patch.ts","../src/types.ts","../src/em.ts","../src/ms.ts","../src/helpers.ts","../src/index.ts"],"mappings":";;;AAAM,UAAW,YAAY;;;;;AAMvB,UAAW,eAAe;;;;AAK1B,UAAW,gBAAgB;;;;;AAM3B,UAAW,aAAa;;;;;AAMxB,KAAM,SAAS,GAAG,YAAY,YAAY,eAAe,GAAG,gBAAgB,YAAY,aAAa;;ACpBrG,UAAW,OAAO;;;;kBAIR,KAAK,CAAC,QAAQ;;;;;;YAMpB,SAAS;gBACL,IAAI;gBACJ,IAAI;;AAGZ,UAAW,UAAU;aAChB,gBAAgB;UACnB,gBAAgB;YACd,SAAS;;AAGb,UAAW,YAAY;;;;;kBAKb,gBAAgB;kBAChB,gBAAgB;;;;AAK1B,KAAM,WAAW,MAAM,KAAK;;cAAiC,YAAY;;AAEzE,KAAM,IAAI,GAAG,MAAM;AAEnB,KAAM,QAAQ,GAAG,MAAM;AAEvB,UAAW,aAAa;;;;;;oBAMZ,gBAAgB,QAAQ,OAAO,CAAC,IAAI,IAAI,IAAI;sBAC1C,gBAAgB,QAAQ,OAAO;wBAC7B,gBAAgB,QAAQ,OAAO,CAAC,QAAQ,IAAI,QAAQ;;;uBAGrD,gBAAgB,UAAU,OAAO;sBAClC,KAAK;;;ACnDzB,cAAM,iBAAkB,SAAQ,YAAY;;AAC5C,cAAM,EAAE,mBAA0B;;ACKlC,cAAa,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCZ,KAAM,IAAI,gBAAgB,KAAK;AAE/B,KAAM,QAAQ,sCAAsC,IAAI,kBAAkB,IAAI;;AC6FpF,cAAa,kBAAkB,QAAe,QAAQ,oBAAoB,KAAK,cAAY,OAAO;;AC1HlG,cAAa,kBAAkB,cAAe,MAAM,WAAW,aAAa","names":[]}
1
+ {"version":3,"file":"index.d.cts","sources":["../src/json-patch.ts","../src/types.ts","../src/em.ts","../src/ms.ts","../src/helpers.ts","../src/index.ts"],"mappings":";;;AAAM,UAAW,YAAY;;;;;AAMvB,UAAW,eAAe;;;;AAK1B,UAAW,gBAAgB;;;;;AAM3B,UAAW,aAAa;;;;;AAMxB,KAAM,SAAS,GAAG,YAAY,YAAY,eAAe,GAAG,gBAAgB,YAAY,aAAa;;ACpBrG,UAAW,OAAO;;;;kBAIR,KAAK,CAAC,QAAQ;;;;;;YAMpB,SAAS;gBACL,IAAI;gBACJ,IAAI;;AAGZ,UAAW,UAAU;aAChB,gBAAgB;UACnB,gBAAgB;YACd,SAAS;;AAGb,UAAW,YAAY;;;;;kBAKb,gBAAgB;kBAChB,gBAAgB;;;cAGpB,aAAa;;AAGnB,KAAM,WAAW,MAAM,KAAK;;cAAiC,YAAY;;AAEzE,KAAM,IAAI,GAAG,MAAM;AAEnB,KAAM,QAAQ,GAAG,MAAM;AAEvB,UAAW,aAAa;;;;;;oBAMZ,gBAAgB,QAAQ,OAAO,CAAC,IAAI,IAAI,IAAI;sBAC1C,gBAAgB,QAAQ,OAAO;wBAC7B,gBAAgB,QAAQ,OAAO,CAAC,QAAQ,IAAI,QAAQ;;;uBAGrD,gBAAgB,UAAU,OAAO;sBAClC,KAAK;;;ACpDzB,cAAM,iBAAkB,SAAQ,YAAY;;AAC5C,cAAM,EAAE,mBAA0B;;ACKlC,cAAa,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCZ,KAAM,IAAI,gBAAgB,KAAK;AAE/B,KAAM,QAAQ,sCAAsC,IAAI,kBAAkB,IAAI;;ACoGpF,cAAa,kBAAkB,QAAe,QAAQ,oBAAoB,KAAK,cAAY,OAAO;;ACjIlG,cAAa,kBAAkB,cAAe,MAAM,WAAW,aAAa","names":[]}
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { Types, Query, HydratedDocument, Schema } from 'mongoose';
1
+ import { Types, Query, HydratedDocument, ClientSession, Schema } from 'mongoose';
2
2
  import EventEmitter from 'node:events';
3
3
 
4
4
  interface AddOperation<T> {
@@ -50,6 +50,7 @@ interface PatchContext<T> {
50
50
  deletedDocs?: HydratedDocument<T>[];
51
51
  ignoreEvent?: boolean;
52
52
  ignorePatchHistory?: boolean;
53
+ session?: ClientSession | null;
53
54
  }
54
55
  type HookContext<T> = Query<T, T> & {
55
56
  op: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sources":["../src/json-patch.ts","../src/types.ts","../src/em.ts","../src/ms.ts","../src/helpers.ts","../src/index.ts"],"mappings":";;;AAAM,UAAW,YAAY;;;;;AAMvB,UAAW,eAAe;;;;AAK1B,UAAW,gBAAgB;;;;;AAM3B,UAAW,aAAa;;;;;AAMxB,KAAM,SAAS,GAAG,YAAY,YAAY,eAAe,GAAG,gBAAgB,YAAY,aAAa;;ACpBrG,UAAW,OAAO;;;;kBAIR,KAAK,CAAC,QAAQ;;;;;;YAMpB,SAAS;gBACL,IAAI;gBACJ,IAAI;;AAGZ,UAAW,UAAU;aAChB,gBAAgB;UACnB,gBAAgB;YACd,SAAS;;AAGb,UAAW,YAAY;;;;;kBAKb,gBAAgB;kBAChB,gBAAgB;;;;AAK1B,KAAM,WAAW,MAAM,KAAK;;cAAiC,YAAY;;AAEzE,KAAM,IAAI,GAAG,MAAM;AAEnB,KAAM,QAAQ,GAAG,MAAM;AAEvB,UAAW,aAAa;;;;;;oBAMZ,gBAAgB,QAAQ,OAAO,CAAC,IAAI,IAAI,IAAI;sBAC1C,gBAAgB,QAAQ,OAAO;wBAC7B,gBAAgB,QAAQ,OAAO,CAAC,QAAQ,IAAI,QAAQ;;;uBAGrD,gBAAgB,UAAU,OAAO;sBAClC,KAAK;;;ACnDzB,cAAM,iBAAkB,SAAQ,YAAY;;AAC5C,cAAM,EAAE,mBAA0B;;ACKlC,cAAa,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCZ,KAAM,IAAI,gBAAgB,KAAK;AAE/B,KAAM,QAAQ,sCAAsC,IAAI,kBAAkB,IAAI;;AC6FpF,cAAa,kBAAkB,QAAe,QAAQ,oBAAoB,KAAK,cAAY,OAAO;;AC1HlG,cAAa,kBAAkB,cAAe,MAAM,WAAW,aAAa","names":[]}
1
+ {"version":3,"file":"index.d.mts","sources":["../src/json-patch.ts","../src/types.ts","../src/em.ts","../src/ms.ts","../src/helpers.ts","../src/index.ts"],"mappings":";;;AAAM,UAAW,YAAY;;;;;AAMvB,UAAW,eAAe;;;;AAK1B,UAAW,gBAAgB;;;;;AAM3B,UAAW,aAAa;;;;;AAMxB,KAAM,SAAS,GAAG,YAAY,YAAY,eAAe,GAAG,gBAAgB,YAAY,aAAa;;ACpBrG,UAAW,OAAO;;;;kBAIR,KAAK,CAAC,QAAQ;;;;;;YAMpB,SAAS;gBACL,IAAI;gBACJ,IAAI;;AAGZ,UAAW,UAAU;aAChB,gBAAgB;UACnB,gBAAgB;YACd,SAAS;;AAGb,UAAW,YAAY;;;;;kBAKb,gBAAgB;kBAChB,gBAAgB;;;cAGpB,aAAa;;AAGnB,KAAM,WAAW,MAAM,KAAK;;cAAiC,YAAY;;AAEzE,KAAM,IAAI,GAAG,MAAM;AAEnB,KAAM,QAAQ,GAAG,MAAM;AAEvB,UAAW,aAAa;;;;;;oBAMZ,gBAAgB,QAAQ,OAAO,CAAC,IAAI,IAAI,IAAI;sBAC1C,gBAAgB,QAAQ,OAAO;wBAC7B,gBAAgB,QAAQ,OAAO,CAAC,QAAQ,IAAI,QAAQ;;;uBAGrD,gBAAgB,UAAU,OAAO;sBAClC,KAAK;;;ACpDzB,cAAM,iBAAkB,SAAQ,YAAY;;AAC5C,cAAM,EAAE,mBAA0B;;ACKlC,cAAa,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCZ,KAAM,IAAI,gBAAgB,KAAK;AAE/B,KAAM,QAAQ,sCAAsC,IAAI,kBAAkB,IAAI;;ACoGpF,cAAa,kBAAkB,QAAe,QAAQ,oBAAoB,KAAK,cAAY,OAAO;;ACjIlG,cAAa,kBAAkB,cAAe,MAAM,WAAW,aAAa","names":[]}
package/dist/index.mjs CHANGED
@@ -200,6 +200,7 @@ const cloneDeep = (value, seen = /* @__PURE__ */ new WeakMap()) => {
200
200
  }
201
201
  return cloneCollection(value, seen);
202
202
  };
203
+ const HISTORY_BATCH_SIZE = 1e3;
203
204
  const chunk = (array, size) => {
204
205
  const result = [];
205
206
  for (let i = 0; i < array.length; i += size) {
@@ -210,6 +211,7 @@ const chunk = (array, size) => {
210
211
  const isHookIgnored = (options) => {
211
212
  return options.ignoreHook === true || options.ignoreEvent === true && options.ignorePatchHistory === true;
212
213
  };
214
+ const sessionOptions = (session) => session ? { session } : {};
213
215
  const toObjectOptions = {
214
216
  depopulate: true,
215
217
  virtuals: false
@@ -404,8 +406,20 @@ const getMetadata = async (opts, doc) => getOptionalField(opts.getMetadata, doc)
404
406
  const getValue = (item) => {
405
407
  return item.status === "fulfilled" ? item.value : void 0;
406
408
  };
407
- const getData = async (opts, doc) => {
409
+ const reportedGetters = /* @__PURE__ */ new WeakMap();
410
+ const reportRejections = (opts, context, results) => {
411
+ const onError = opts.onError ?? console.error;
412
+ const reported = context ? reportedGetters.get(context) ?? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set();
413
+ if (context) reportedGetters.set(context, reported);
414
+ for (const [index, result] of results.entries()) {
415
+ if (result.status === "fulfilled" || reported.has(index)) continue;
416
+ reported.add(index);
417
+ onError(result.reason instanceof Error ? result.reason : new Error(String(result.reason)));
418
+ }
419
+ };
420
+ const getData = async (opts, doc, context) => {
408
421
  return Promise.allSettled([getUser(opts, doc), getReason(opts, doc), getMetadata(opts, doc)]).then(([user, reason, metadata]) => {
422
+ reportRejections(opts, context, [user, reason, metadata]);
409
423
  return [getValue(user), getValue(reason), getValue(metadata)];
410
424
  });
411
425
  };
@@ -423,14 +437,14 @@ const bulkPatch = async (opts, context, eventKey, docsKey) => {
423
437
  const docs = context[docsKey];
424
438
  const key = eventKey === "eventCreated" ? "doc" : "oldDoc";
425
439
  if (isEmpty(docs) || !docs || !event && !history) return;
426
- const chunks = chunk(docs, 1e3);
440
+ const chunks = chunk(docs, HISTORY_BATCH_SIZE);
427
441
  for (const batch of chunks) {
428
442
  const bulk = [];
429
443
  for (const doc of batch) {
430
444
  const omitted = getObjectOmit(opts, doc);
431
445
  emitEvent(context, event, { [key]: omitted });
432
446
  if (history) {
433
- const [user, reason, metadata] = await getData(opts, doc);
447
+ const [user, reason, metadata] = await getData(opts, doc, context);
434
448
  bulk.push({
435
449
  insertOne: {
436
450
  document: {
@@ -450,7 +464,7 @@ const bulkPatch = async (opts, context, eventKey, docsKey) => {
450
464
  }
451
465
  if (history && !isEmpty(bulk)) {
452
466
  const onError = opts.onError ?? console.error;
453
- await HistoryModel.bulkWrite(bulk, { ordered: false }).catch((error) => {
467
+ await HistoryModel.bulkWrite(bulk, { ordered: false, ...sessionOptions(context.session) }).catch((error) => {
454
468
  onError(error);
455
469
  });
456
470
  }
@@ -459,36 +473,68 @@ const bulkPatch = async (opts, context, eventKey, docsKey) => {
459
473
  const createPatch = async (opts, context) => {
460
474
  await bulkPatch(opts, context, "eventCreated", "createdDocs");
461
475
  };
462
- const updatePatch = async (opts, context, current, original) => {
463
- const history = isPatchHistoryEnabled(opts, context);
476
+ const diffAndEmit = (opts, context, current, original) => {
464
477
  const currentObject = getJsonOmit(opts, current);
465
478
  const originalObject = getJsonOmit(opts, original);
466
- if (isEmpty(originalObject) || isEmpty(currentObject)) return;
479
+ if (isEmpty(originalObject) || isEmpty(currentObject)) return void 0;
467
480
  const patch = compare(originalObject, currentObject, true);
468
- if (isEmpty(patch)) return;
481
+ if (isEmpty(patch)) return void 0;
469
482
  emitEvent(context, opts.eventUpdated, { oldDoc: original, doc: current, patch });
470
- if (history) {
471
- let version = 0;
472
- const lastHistory = await HistoryModel.findOne({ collectionId: original._id }).sort("-version").exec();
473
- if (lastHistory) {
474
- version = lastHistory.version + 1;
483
+ return patch;
484
+ };
485
+ const updateEntry = (context, original, patch, version, [user, reason, metadata]) => ({
486
+ op: context.op,
487
+ modelName: context.modelName,
488
+ collectionName: context.collectionName,
489
+ collectionId: original._id,
490
+ patch,
491
+ version,
492
+ ...user !== void 0 && { user },
493
+ ...reason !== void 0 && { reason },
494
+ ...metadata !== void 0 && { metadata }
495
+ });
496
+ const updatePatch = async (opts, context, current, original) => {
497
+ const patch = diffAndEmit(opts, context, current, original);
498
+ if (!patch || !isPatchHistoryEnabled(opts, context)) return;
499
+ let version = 0;
500
+ const lastHistory = await HistoryModel.findOne({ collectionId: original._id }, null, sessionOptions(context.session)).sort("-version").exec();
501
+ if (lastHistory) {
502
+ version = lastHistory.version + 1;
503
+ }
504
+ const data = await getData(opts, current, context);
505
+ const onError = opts.onError ?? console.error;
506
+ await HistoryModel.create([updateEntry(context, original, patch, version, data)], sessionOptions(context.session)).catch((error) => {
507
+ onError(error);
508
+ });
509
+ };
510
+ const nextVersions = async (ids, session) => {
511
+ const last = await HistoryModel.aggregate([{ $match: { collectionId: { $in: ids } } }, { $group: { _id: "$collectionId", version: { $max: "$version" } } }]).option(sessionOptions(session)).exec();
512
+ return new Map(last.map(({ _id, version }) => [String(_id), version + 1]));
513
+ };
514
+ const updatePatchBatch = async (opts, context, pairs) => {
515
+ const [first] = pairs;
516
+ if (pairs.length === 1 && first) {
517
+ await updatePatch(opts, context, first.current, first.original);
518
+ return;
519
+ }
520
+ const history = isPatchHistoryEnabled(opts, context);
521
+ const pending = [];
522
+ for (const { current, original } of pairs) {
523
+ const patch = diffAndEmit(opts, context, current, original);
524
+ if (patch && history) {
525
+ pending.push({ original, patch, data: await getData(opts, current, context) });
475
526
  }
476
- const [user, reason, metadata] = await getData(opts, current);
477
- const onError = opts.onError ?? console.error;
478
- await HistoryModel.create({
479
- op: context.op,
480
- modelName: context.modelName,
481
- collectionName: context.collectionName,
482
- collectionId: original._id,
483
- patch,
484
- version,
485
- ...user !== void 0 && { user },
486
- ...reason !== void 0 && { reason },
487
- ...metadata !== void 0 && { metadata }
488
- }).catch((error) => {
489
- onError(error);
490
- });
491
527
  }
528
+ if (isEmpty(pending)) return;
529
+ const versions = await nextVersions(
530
+ pending.map(({ original }) => original._id),
531
+ context.session
532
+ );
533
+ const entries = pending.map(({ original, patch, data }) => updateEntry(context, original, patch, versions.get(String(original._id)) ?? 0, data));
534
+ const onError = opts.onError ?? console.error;
535
+ await HistoryModel.insertMany(entries, { ordered: false, ...sessionOptions(context.session) }).catch((error) => {
536
+ onError(error);
537
+ });
492
538
  };
493
539
  const deletePatch = async (opts, context) => {
494
540
  await bulkPatch(opts, context, "eventDeleted", "deletedDocs");
@@ -506,15 +552,16 @@ const deleteHooksInitialize = (schema, opts) => {
506
552
  modelName: opts.modelName ?? model.modelName,
507
553
  collectionName: opts.collectionName ?? model.collection.collectionName,
508
554
  ignoreEvent: options.ignoreEvent,
509
- ignorePatchHistory: options.ignorePatchHistory
555
+ ignorePatchHistory: options.ignorePatchHistory,
556
+ session: options.session ?? null
510
557
  };
511
558
  if (["remove", "deleteMany"].includes(this._context.op) && !options.single) {
512
- const docs = await model.find(filter).lean().exec();
559
+ const docs = await model.find(filter, null, sessionOptions(options.session)).lean().exec();
513
560
  if (!isEmpty(docs)) {
514
561
  this._context.deletedDocs = docs;
515
562
  }
516
563
  } else {
517
- const doc = await model.findOne(filter).lean().exec();
564
+ const doc = await model.findOne(filter, null, sessionOptions(options.session)).lean().exec();
518
565
  if (!isEmpty(doc)) {
519
566
  this._context.deletedDocs = [doc];
520
567
  }
@@ -540,12 +587,13 @@ const saveHooksInitialize = (schema, opts) => {
540
587
  op: this.isNew ? "create" : "update",
541
588
  modelName: opts.modelName ?? model.modelName,
542
589
  collectionName: opts.collectionName ?? model.collection.collectionName,
543
- createdDocs: [current]
590
+ createdDocs: [current],
591
+ session: this.$session()
544
592
  };
545
593
  if (this.isNew) {
546
594
  await createPatch(opts, context);
547
595
  } else {
548
- const original = await model.findById(current._id).lean().exec();
596
+ const original = await model.findById(current._id, null, sessionOptions(context.session)).lean().exec();
549
597
  if (original) {
550
598
  await updatePatch(opts, context, current, original);
551
599
  }
@@ -782,17 +830,24 @@ const updateHooksInitialize = (schema, opts) => {
782
830
  op: this.op,
783
831
  modelName: opts.modelName ?? model.modelName,
784
832
  collectionName: opts.collectionName ?? model.collection.collectionName,
785
- isNew: Boolean(options.upsert) && await model.countDocuments(filter).exec() === 0,
833
+ isNew: Boolean(options.upsert) && await model.countDocuments(filter, sessionOptions(options.session)).exec() === 0,
786
834
  ignoreEvent: options.ignoreEvent,
787
- ignorePatchHistory: options.ignorePatchHistory
835
+ ignorePatchHistory: options.ignorePatchHistory,
836
+ session: options.session ?? null
788
837
  };
789
838
  const updateQuery = this.getUpdate();
790
839
  const { update, commands } = splitUpdateAndCommands(updateQuery);
791
- const cursor = model.find(filter).cursor();
792
- await cursor.eachAsync(async (doc) => {
793
- const origDoc = doc.toObject(toObjectOptions);
794
- await updatePatch(opts, this._context, assignUpdate(doc, update, commands), origDoc);
795
- });
840
+ const cursor = model.find(filter, null, sessionOptions(options.session)).cursor();
841
+ await cursor.eachAsync(
842
+ async (docs) => {
843
+ const pairs = docs.map((doc) => {
844
+ const original = doc.toObject(toObjectOptions);
845
+ return { current: assignUpdate(doc, update, commands), original };
846
+ });
847
+ await updatePatchBatch(opts, this._context, pairs);
848
+ },
849
+ { batchSize: HISTORY_BATCH_SIZE }
850
+ );
796
851
  });
797
852
  schema.post(updateMethods, { document: false, query: true }, async function() {
798
853
  const options = this.getOptions();
@@ -809,7 +864,7 @@ const updateHooksInitialize = (schema, opts) => {
809
864
  let current = null;
810
865
  for (const query of candidates) {
811
866
  if (current || isEmpty(query)) continue;
812
- const found = await model.findOne(query).sort({ _id: -1 }).lean().exec();
867
+ const found = await model.findOne(query, null, sessionOptions(this._context.session)).sort({ _id: -1 }).lean().exec();
813
868
  current = found;
814
869
  }
815
870
  if (current) {
@@ -837,7 +892,9 @@ const patchHistoryPlugin = (schema, opts) => {
837
892
  op: "create",
838
893
  modelName: opts.modelName ?? this.modelName,
839
894
  collectionName: opts.collectionName ?? this.collection.collectionName,
840
- createdDocs: docs
895
+ createdDocs: docs,
896
+ // insertMany sets the session of its options on every hydrated document; lean ones carry none
897
+ session: docs[0]?.$session?.() ?? null
841
898
  };
842
899
  await createPatch(opts, context);
843
900
  });
@@ -856,7 +913,8 @@ const patchHistoryPlugin = (schema, opts) => {
856
913
  op: "delete",
857
914
  modelName: opts.modelName ?? model.modelName,
858
915
  collectionName: opts.collectionName ?? model.collection.collectionName,
859
- deletedDocs: [original]
916
+ deletedDocs: [original],
917
+ session: this.$session()
860
918
  };
861
919
  await deletePatch(opts, context);
862
920
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ts-patch-mongoose",
3
- "version": "4.0.2",
3
+ "version": "4.1.0",
4
4
  "description": "Patch history & events for mongoose models",
5
5
  "author": "ilovepixelart",
6
6
  "license": "MIT",
@@ -59,6 +59,7 @@
59
59
  "scripts": {
60
60
  "biome": "npx @biomejs/biome check",
61
61
  "biome:fix": "npx @biomejs/biome check --write .",
62
+ "lint:package": "publint --strict && attw --pack .",
62
63
  "test": "vitest run --coverage",
63
64
  "test:open": "vitest run --coverage && open-cli coverage/lcov-report/index.html",
64
65
  "clean": "rm -rf ./dist",
@@ -68,8 +69,9 @@
68
69
  "release": "npm install && npm run biome && npm run type:check && npm run type:check:tests && npm run build && np --no-publish"
69
70
  },
70
71
  "devDependencies": {
72
+ "@arethetypeswrong/cli": "0.18.5",
71
73
  "@biomejs/biome": "2.6.8",
72
- "@types/node": "25.9.9",
74
+ "@types/node": "22.20.5",
73
75
  "@typescript/typescript6": "6.0.2",
74
76
  "@vitest/coverage-v8": "5.1.0",
75
77
  "fast-check": "4.10.2",
@@ -77,6 +79,7 @@
77
79
  "mongoose": "9.12.2",
78
80
  "open-cli": "9.0.0",
79
81
  "pkgroll": "2.29.1",
82
+ "publint": "0.3.25",
80
83
  "simple-git-hooks": "2.14.0",
81
84
  "typescript": "7.0.2",
82
85
  "vitest": "5.1.0"
@@ -86,7 +89,7 @@
86
89
  },
87
90
  "simple-git-hooks": {
88
91
  "pre-commit": "npm run type:check",
89
- "pre-push": "npm run biome:fix"
92
+ "pre-push": "npm run biome"
90
93
  },
91
94
  "np": {
92
95
  "publish": false