@event-driven-io/emmett-esdb 0.43.0-apha.2 → 0.43.0-beta.10

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.cjs CHANGED
@@ -1,6 +1,5 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;// ../emmett/dist/chunk-AZDDB5SF.js
2
2
  var isNumber = (val) => typeof val === "number" && val === val;
3
- var isBigint = (val) => typeof val === "bigint" && val === val;
4
3
  var isString = (val) => typeof val === "string";
5
4
  var EmmettError = (_class = class _EmmettError extends Error {
6
5
  static __initStatic() {this.Codes = {
@@ -35,7 +34,7 @@ var ConcurrencyError = class _ConcurrencyError extends EmmettError {
35
34
  constructor(current, expected, message) {
36
35
  super({
37
36
  errorCode: EmmettError.Codes.ConcurrencyError,
38
- message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _2 => _2.toString, 'call', _3 => _3()])}`))
37
+ message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _ => _.toString, 'call', _2 => _2()])}`))
39
38
  });
40
39
  this.current = current;
41
40
  this.expected = expected;
@@ -55,9 +54,11 @@ var ConcurrencyInMemoryDatabaseError = class _ConcurrencyInMemoryDatabaseError e
55
54
  // ../emmett/dist/index.js
56
55
  var _uuid = require('uuid');
57
56
 
57
+
58
58
  var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);
59
59
 
60
60
 
61
+
61
62
  var emmettPrefix = "emt";
62
63
  var defaultTag = `${emmettPrefix}:default`;
63
64
  var unknownTag = `${emmettPrefix}:unknown`;
@@ -77,7 +78,7 @@ var assertExpectedVersionMatchesCurrent = (current, expected, defaultVersion) =>
77
78
  };
78
79
  var ExpectedVersionConflictError = class _ExpectedVersionConflictError extends ConcurrencyError {
79
80
  constructor(current, expected) {
80
- super(_optionalChain([current, 'optionalAccess', _4 => _4.toString, 'call', _5 => _5()]), _optionalChain([expected, 'optionalAccess', _6 => _6.toString, 'call', _7 => _7()]));
81
+ super(_optionalChain([current, 'optionalAccess', _3 => _3.toString, 'call', _4 => _4()]), _optionalChain([expected, 'optionalAccess', _5 => _5.toString, 'call', _6 => _6()]));
81
82
  Object.setPrototypeOf(this, _ExpectedVersionConflictError.prototype);
82
83
  }
83
84
  };
@@ -282,45 +283,131 @@ var deepEquals = (left, right) => {
282
283
  var isEquatable = (left) => {
283
284
  return left !== null && left !== void 0 && typeof left === "object" && "equals" in left && typeof left["equals"] === "function";
284
285
  };
285
- var ParseError = class extends Error {
286
- constructor(text) {
287
- super(`Cannot parse! ${text}`);
286
+ var toNormalizedString = (value) => value.toString().padStart(19, "0");
287
+ var bigInt = {
288
+ toNormalizedString
289
+ };
290
+ var bigIntReplacer = (_key, value) => {
291
+ return typeof value === "bigint" ? value.toString() : value;
292
+ };
293
+ var dateReplacer = (_key, value) => {
294
+ return value instanceof Date ? value.toISOString() : value;
295
+ };
296
+ var isFirstLetterNumeric = (str) => {
297
+ const c = str.charCodeAt(0);
298
+ return c >= 48 && c <= 57;
299
+ };
300
+ var isFirstLetterNumericOrMinus = (str) => {
301
+ const c = str.charCodeAt(0);
302
+ return c >= 48 && c <= 57 || c === 45;
303
+ };
304
+ var bigIntReviver = (_key, value, context) => {
305
+ if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) {
306
+ try {
307
+ return BigInt(_nullishCoalesce(_optionalChain([context, 'optionalAccess', _7 => _7.source]), () => ( value.toString())));
308
+ } catch (e) {
309
+ return value;
310
+ }
288
311
  }
312
+ if (typeof value === "string" && value.length > 15) {
313
+ if (isFirstLetterNumericOrMinus(value)) {
314
+ const num = Number(value);
315
+ if (Number.isFinite(num) && !Number.isSafeInteger(num)) {
316
+ try {
317
+ return BigInt(value);
318
+ } catch (e2) {
319
+ }
320
+ }
321
+ }
322
+ }
323
+ return value;
289
324
  };
290
- var JSONParser = {
291
- stringify: (value, options) => {
292
- return JSON.stringify(
293
- _optionalChain([options, 'optionalAccess', _8 => _8.map]) ? options.map(value) : value,
294
- //TODO: Consider adding support to DateTime and adding specific format to mark that's a bigint
295
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
296
- (_, v) => typeof v === "bigint" ? v.toString() : v
297
- );
298
- },
299
- parse: (text, options) => {
300
- const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _9 => _9.reviver]));
301
- if (_optionalChain([options, 'optionalAccess', _10 => _10.typeCheck]) && !_optionalChain([options, 'optionalAccess', _11 => _11.typeCheck, 'call', _12 => _12(parsed)]))
302
- throw new ParseError(text);
303
- return _optionalChain([options, 'optionalAccess', _13 => _13.map]) ? options.map(parsed) : parsed;
325
+ var dateReviver = (_key, value) => {
326
+ if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
327
+ const date = new Date(value);
328
+ if (!isNaN(date.getTime())) {
329
+ return date;
330
+ }
304
331
  }
332
+ return value;
333
+ };
334
+ var composeJSONReplacers = (...replacers) => {
335
+ const filteredReplacers = replacers.filter((r) => r !== void 0);
336
+ if (filteredReplacers.length === 0) return void 0;
337
+ return (key, value) => (
338
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
339
+ filteredReplacers.reduce(
340
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
341
+ (accValue, replacer) => replacer(key, accValue),
342
+ value
343
+ )
344
+ );
345
+ };
346
+ var composeJSONRevivers = (...revivers) => {
347
+ const filteredRevivers = revivers.filter((r) => r !== void 0);
348
+ if (filteredRevivers.length === 0) return void 0;
349
+ return (key, value, context) => (
350
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
351
+ filteredRevivers.reduce(
352
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
353
+ (accValue, reviver) => reviver(key, accValue, context),
354
+ value
355
+ )
356
+ );
357
+ };
358
+ var JSONReplacer = (opts) => composeJSONReplacers(
359
+ _optionalChain([opts, 'optionalAccess', _8 => _8.replacer]),
360
+ _optionalChain([opts, 'optionalAccess', _9 => _9.failOnBigIntSerialization]) !== true ? JSONReplacers.bigInt : void 0,
361
+ _optionalChain([opts, 'optionalAccess', _10 => _10.useDefaultDateSerialization]) !== true ? JSONReplacers.date : void 0
362
+ );
363
+ var JSONReviver = (opts) => composeJSONRevivers(
364
+ _optionalChain([opts, 'optionalAccess', _11 => _11.reviver]),
365
+ _optionalChain([opts, 'optionalAccess', _12 => _12.parseBigInts]) === true ? JSONRevivers.bigInt : void 0,
366
+ _optionalChain([opts, 'optionalAccess', _13 => _13.parseDates]) === true ? JSONRevivers.date : void 0
367
+ );
368
+ var JSONReplacers = {
369
+ bigInt: bigIntReplacer,
370
+ date: dateReplacer
305
371
  };
372
+ var JSONRevivers = {
373
+ bigInt: bigIntReviver,
374
+ date: dateReviver
375
+ };
376
+ var jsonSerializer = (options) => {
377
+ const defaultReplacer = JSONReplacer(options);
378
+ const defaultReviver = JSONReviver(options);
379
+ return {
380
+ serialize: (object, serializerOptions) => JSON.stringify(
381
+ object,
382
+ serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer
383
+ ),
384
+ deserialize: (payload, deserializerOptions) => JSON.parse(
385
+ payload,
386
+ deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver
387
+ )
388
+ };
389
+ };
390
+ var JSONSerializer = Object.assign(jsonSerializer(), {
391
+ from: (options) => _nullishCoalesce(_optionalChain([options, 'optionalAccess', _14 => _14.serialization, 'optionalAccess', _15 => _15.serializer]), () => ( (_optionalChain([options, 'optionalAccess', _16 => _16.serialization, 'optionalAccess', _17 => _17.options]) ? jsonSerializer(_optionalChain([options, 'optionalAccess', _18 => _18.serialization, 'optionalAccess', _19 => _19.options])) : JSONSerializer)))
392
+ });
306
393
  var asyncRetry = async (fn, opts) => {
307
394
  if (opts === void 0 || opts.retries === 0) return fn();
308
395
  return _asyncretry2.default.call(void 0,
309
396
  async (bail) => {
310
397
  try {
311
398
  const result = await fn();
312
- if (_optionalChain([opts, 'optionalAccess', _14 => _14.shouldRetryResult]) && opts.shouldRetryResult(result)) {
399
+ if (_optionalChain([opts, 'optionalAccess', _20 => _20.shouldRetryResult]) && opts.shouldRetryResult(result)) {
313
400
  throw new EmmettError(
314
- `Retrying because of result: ${JSONParser.stringify(result)}`
401
+ `Retrying because of result: ${JSONSerializer.serialize(result)}`
315
402
  );
316
403
  }
317
404
  return result;
318
- } catch (error2) {
319
- if (_optionalChain([opts, 'optionalAccess', _15 => _15.shouldRetryError]) && !opts.shouldRetryError(error2)) {
320
- bail(error2);
405
+ } catch (error) {
406
+ if (_optionalChain([opts, 'optionalAccess', _21 => _21.shouldRetryError]) && !opts.shouldRetryError(error)) {
407
+ bail(error);
321
408
  return void 0;
322
409
  }
323
- throw error2;
410
+ throw error;
324
411
  }
325
412
  },
326
413
  _nullishCoalesce(opts, () => ( { retries: 0 }))
@@ -367,11 +454,11 @@ var operationResult = (result, options) => {
367
454
  const { operationName, collectionName } = options;
368
455
  if (!successful)
369
456
  throw new ConcurrencyInMemoryDatabaseError(
370
- _nullishCoalesce(errorMessage, () => ( `${operationName} on ${collectionName} failed. Expected document state does not match current one! Result: ${JSONParser.stringify(result)}!`))
457
+ _nullishCoalesce(errorMessage, () => ( `${operationName} on ${collectionName} failed. Expected document state does not match current one! Result: ${JSONSerializer.serialize(result)}!`))
371
458
  );
372
459
  }
373
460
  };
374
- if (_optionalChain([options, 'access', _16 => _16.errors, 'optionalAccess', _17 => _17.throwOnOperationFailures]))
461
+ if (_optionalChain([options, 'access', _22 => _22.errors, 'optionalAccess', _23 => _23.throwOnOperationFailures]))
375
462
  operationResult2.assertSuccessful();
376
463
  return operationResult2;
377
464
  };
@@ -416,14 +503,14 @@ var getInMemoryDatabase = () => {
416
503
  findOne: (predicate) => {
417
504
  ensureCollectionCreated();
418
505
  const documentsInCollection = storage.get(collectionName);
419
- const filteredDocuments = predicate ? _optionalChain([documentsInCollection, 'optionalAccess', _18 => _18.filter, 'call', _19 => _19((doc) => predicate(doc))]) : documentsInCollection;
420
- const firstOne = _nullishCoalesce(_optionalChain([filteredDocuments, 'optionalAccess', _20 => _20[0]]), () => ( null));
506
+ const filteredDocuments = predicate ? _optionalChain([documentsInCollection, 'optionalAccess', _24 => _24.filter, 'call', _25 => _25((doc) => predicate(doc))]) : documentsInCollection;
507
+ const firstOne = _nullishCoalesce(_optionalChain([filteredDocuments, 'optionalAccess', _26 => _26[0]]), () => ( null));
421
508
  return Promise.resolve(firstOne);
422
509
  },
423
510
  find: (predicate) => {
424
511
  ensureCollectionCreated();
425
512
  const documentsInCollection = storage.get(collectionName);
426
- const filteredDocuments = predicate ? _optionalChain([documentsInCollection, 'optionalAccess', _21 => _21.filter, 'call', _22 => _22((doc) => predicate(doc))]) : documentsInCollection;
513
+ const filteredDocuments = predicate ? _optionalChain([documentsInCollection, 'optionalAccess', _27 => _27.filter, 'call', _28 => _28((doc) => predicate(doc))]) : documentsInCollection;
427
514
  return Promise.resolve(filteredDocuments);
428
515
  },
429
516
  deleteOne: (predicate) => {
@@ -495,7 +582,7 @@ var getInMemoryDatabase = () => {
495
582
  );
496
583
  }
497
584
  const existing = documentsInCollection[firstIndex];
498
- if (typeof _optionalChain([options, 'optionalAccess', _23 => _23.expectedVersion]) === "bigint" && existing._version !== options.expectedVersion) {
585
+ if (typeof _optionalChain([options, 'optionalAccess', _29 => _29.expectedVersion]) === "bigint" && existing._version !== options.expectedVersion) {
499
586
  return Promise.resolve(
500
587
  operationResult(
501
588
  {
@@ -600,73 +687,20 @@ var getInMemoryDatabase = () => {
600
687
  }
601
688
  };
602
689
  };
603
- var downcastRecordedMessage = (recordedMessage, options) => {
604
- if (!_optionalChain([options, 'optionalAccess', _24 => _24.downcast]))
605
- return recordedMessage;
606
- const downcasted = options.downcast(
607
- recordedMessage
608
- );
609
- return {
610
- ...recordedMessage,
611
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
612
- data: downcasted.data,
613
- ..."metadata" in recordedMessage || "metadata" in downcasted ? {
614
- metadata: {
615
- ..."metadata" in recordedMessage ? recordedMessage.metadata : {},
616
- ..."metadata" in downcasted ? downcasted.metadata : {}
617
- }
618
- } : {}
619
- };
620
- };
621
- var downcastRecordedMessages = (recordedMessages, options) => {
622
- if (!_optionalChain([options, 'optionalAccess', _25 => _25.downcast]))
623
- return recordedMessages;
624
- return recordedMessages.map(
625
- (recordedMessage) => downcastRecordedMessage(recordedMessage, options)
626
- );
627
- };
628
- var upcastRecordedMessage = (recordedMessage, options) => {
629
- if (!_optionalChain([options, 'optionalAccess', _26 => _26.upcast]))
630
- return recordedMessage;
631
- const upcasted = options.upcast(
632
- recordedMessage
633
- );
634
- return {
635
- ...recordedMessage,
636
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
637
- data: upcasted.data,
638
- ..."metadata" in recordedMessage || "metadata" in upcasted ? {
639
- metadata: {
640
- ..."metadata" in recordedMessage ? recordedMessage.metadata : {},
641
- ..."metadata" in upcasted ? upcasted.metadata : {}
642
- }
643
- } : {}
644
- };
645
- };
646
690
  var getCheckpoint = (message2) => {
647
- return "checkpoint" in message2.metadata ? (
648
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
649
- message2.metadata.checkpoint
650
- ) : "globalPosition" in message2.metadata && // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
651
- isBigint(message2.metadata.globalPosition) ? (
652
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
653
- message2.metadata.globalPosition
654
- ) : "streamPosition" in message2.metadata && // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
655
- isBigint(message2.metadata.streamPosition) ? (
656
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
657
- message2.metadata.streamPosition
658
- ) : null;
691
+ return message2.metadata.checkpoint;
659
692
  };
660
693
  var wasMessageHandled = (message2, checkpoint) => {
661
694
  const messageCheckpoint = getCheckpoint(message2);
662
- const checkpointBigint = checkpoint;
663
- return messageCheckpoint !== null && messageCheckpoint !== void 0 && checkpointBigint !== null && checkpointBigint !== void 0 && messageCheckpoint <= checkpointBigint;
695
+ return messageCheckpoint !== null && messageCheckpoint !== void 0 && checkpoint !== null && checkpoint !== void 0 && messageCheckpoint <= checkpoint;
664
696
  };
665
697
  var MessageProcessorType = {
666
698
  PROJECTOR: "projector",
667
699
  REACTOR: "reactor"
668
700
  };
669
701
  var defaultProcessingMessageProcessingScope = (handler, partialContext) => handler(partialContext);
702
+ var bigIntProcessorCheckpoint = (value) => bigInt.toNormalizedString(value);
703
+ var parseBigIntProcessorCheckpoint = (value) => BigInt(value);
670
704
  var defaultProcessorVersion = 1;
671
705
  var defaultProcessorPartition = defaultTag;
672
706
  var getProcessorInstanceId = (processorId) => `${processorId}:${_uuid.v7.call(void 0, )}`;
@@ -716,12 +750,13 @@ var reactor = (options) => {
716
750
  id: processorId,
717
751
  instanceId,
718
752
  type,
753
+ canHandle,
719
754
  init,
720
755
  start: async (startOptions) => {
721
756
  if (isActive) return;
722
757
  await init(startOptions);
723
758
  isActive = true;
724
- closeSignal = onShutdown(() => close({}));
759
+ closeSignal = onShutdown(() => close(startOptions));
725
760
  if (lastCheckpoint !== null)
726
761
  return {
727
762
  lastCheckpoint
@@ -732,7 +767,7 @@ var reactor = (options) => {
732
767
  }
733
768
  if (startFrom && startFrom !== "CURRENT") return startFrom;
734
769
  if (checkpoints) {
735
- const readResult = await _optionalChain([checkpoints, 'optionalAccess', _27 => _27.read, 'call', _28 => _28(
770
+ const readResult = await _optionalChain([checkpoints, 'optionalAccess', _30 => _30.read, 'call', _31 => _31(
736
771
  {
737
772
  processorId,
738
773
  partition
@@ -760,7 +795,7 @@ var reactor = (options) => {
760
795
  const upcasted = upcastRecordedMessage(
761
796
  // TODO: Make it smarter
762
797
  message2,
763
- _optionalChain([options, 'access', _29 => _29.messageOptions, 'optionalAccess', _30 => _30.schema, 'optionalAccess', _31 => _31.versioning])
798
+ _optionalChain([options, 'access', _32 => _32.messageOptions, 'optionalAccess', _33 => _33.schema, 'optionalAccess', _34 => _34.versioning])
764
799
  );
765
800
  if (canHandle !== void 0 && !canHandle.includes(upcasted.type))
766
801
  continue;
@@ -813,13 +848,13 @@ var projector = (options) => {
813
848
  processorId,
814
849
  messageOptions: options.projection.eventsOptions,
815
850
  hooks: {
816
- onInit: _optionalChain([options, 'access', _32 => _32.hooks, 'optionalAccess', _33 => _33.onInit]),
817
- onStart: options.truncateOnStart && options.projection.truncate || _optionalChain([options, 'access', _34 => _34.hooks, 'optionalAccess', _35 => _35.onStart]) ? async (context) => {
851
+ onInit: _optionalChain([options, 'access', _35 => _35.hooks, 'optionalAccess', _36 => _36.onInit]),
852
+ onStart: options.truncateOnStart && options.projection.truncate || _optionalChain([options, 'access', _37 => _37.hooks, 'optionalAccess', _38 => _38.onStart]) ? async (context) => {
818
853
  if (options.truncateOnStart && options.projection.truncate)
819
854
  await options.projection.truncate(context);
820
- if (_optionalChain([options, 'access', _36 => _36.hooks, 'optionalAccess', _37 => _37.onStart])) await _optionalChain([options, 'access', _38 => _38.hooks, 'optionalAccess', _39 => _39.onStart, 'call', _40 => _40(context)]);
855
+ if (_optionalChain([options, 'access', _39 => _39.hooks, 'optionalAccess', _40 => _40.onStart])) await _optionalChain([options, 'access', _41 => _41.hooks, 'optionalAccess', _42 => _42.onStart, 'call', _43 => _43(context)]);
821
856
  } : void 0,
822
- onClose: _optionalChain([options, 'access', _41 => _41.hooks, 'optionalAccess', _42 => _42.onClose])
857
+ onClose: _optionalChain([options, 'access', _44 => _44.hooks, 'optionalAccess', _45 => _45.onClose])
823
858
  },
824
859
  eachMessage: async (event2, context) => projection2.handle([event2], context)
825
860
  });
@@ -829,7 +864,7 @@ var inMemoryCheckpointer = () => {
829
864
  read: async ({ processorId }, { database }) => {
830
865
  const checkpoint = await database.collection("emt_processor_checkpoints").findOne((d) => d._id === processorId);
831
866
  return Promise.resolve({
832
- lastCheckpoint: _nullishCoalesce(_optionalChain([checkpoint, 'optionalAccess', _43 => _43.lastCheckpoint]), () => ( null))
867
+ lastCheckpoint: _nullishCoalesce(_optionalChain([checkpoint, 'optionalAccess', _46 => _46.lastCheckpoint]), () => ( null))
833
868
  });
834
869
  },
835
870
  store: async (context, { database }) => {
@@ -840,7 +875,7 @@ var inMemoryCheckpointer = () => {
840
875
  const checkpoint = await checkpoints.findOne(
841
876
  (d) => d._id === processorId
842
877
  );
843
- const currentPosition = _nullishCoalesce(_optionalChain([checkpoint, 'optionalAccess', _44 => _44.lastCheckpoint]), () => ( null));
878
+ const currentPosition = _nullishCoalesce(_optionalChain([checkpoint, 'optionalAccess', _47 => _47.lastCheckpoint]), () => ( null));
844
879
  const newCheckpoint = getCheckpoint(message2);
845
880
  if (currentPosition && (currentPosition === newCheckpoint || currentPosition !== lastCheckpoint)) {
846
881
  return {
@@ -860,7 +895,7 @@ var inMemoryCheckpointer = () => {
860
895
  var inMemoryProcessingScope = (options) => {
861
896
  const processorDatabase = options.database;
862
897
  const processingScope = (handler, partialContext) => {
863
- const database = _nullishCoalesce(processorDatabase, () => ( _optionalChain([partialContext, 'optionalAccess', _45 => _45.database])));
898
+ const database = _nullishCoalesce(processorDatabase, () => ( _optionalChain([partialContext, 'optionalAccess', _48 => _48.database])));
864
899
  if (!database)
865
900
  throw new EmmettError(
866
901
  `InMemory processor '${options.processorId}' is missing database. Ensure that you passed it through options`
@@ -870,12 +905,12 @@ var inMemoryProcessingScope = (options) => {
870
905
  return processingScope;
871
906
  };
872
907
  var inMemoryProjector = (options) => {
873
- const database = _nullishCoalesce(_optionalChain([options, 'access', _46 => _46.connectionOptions, 'optionalAccess', _47 => _47.database]), () => ( getInMemoryDatabase()));
908
+ const database = _nullishCoalesce(_optionalChain([options, 'access', _49 => _49.connectionOptions, 'optionalAccess', _50 => _50.database]), () => ( getInMemoryDatabase()));
874
909
  const hooks = {
875
- onInit: _optionalChain([options, 'access', _48 => _48.hooks, 'optionalAccess', _49 => _49.onInit]),
876
- onStart: _optionalChain([options, 'access', _50 => _50.hooks, 'optionalAccess', _51 => _51.onStart]),
877
- onClose: _optionalChain([options, 'access', _52 => _52.hooks, 'optionalAccess', _53 => _53.onClose]) ? async (context) => {
878
- if (_optionalChain([options, 'access', _54 => _54.hooks, 'optionalAccess', _55 => _55.onClose])) await _optionalChain([options, 'access', _56 => _56.hooks, 'optionalAccess', _57 => _57.onClose, 'call', _58 => _58(context)]);
910
+ onInit: _optionalChain([options, 'access', _51 => _51.hooks, 'optionalAccess', _52 => _52.onInit]),
911
+ onStart: _optionalChain([options, 'access', _53 => _53.hooks, 'optionalAccess', _54 => _54.onStart]),
912
+ onClose: _optionalChain([options, 'access', _55 => _55.hooks, 'optionalAccess', _56 => _56.onClose]) ? async (context) => {
913
+ if (_optionalChain([options, 'access', _57 => _57.hooks, 'optionalAccess', _58 => _58.onClose])) await _optionalChain([options, 'access', _59 => _59.hooks, 'optionalAccess', _60 => _60.onClose, 'call', _61 => _61(context)]);
879
914
  } : void 0
880
915
  };
881
916
  const processor = projector({
@@ -890,11 +925,11 @@ var inMemoryProjector = (options) => {
890
925
  return Object.assign(processor, { database });
891
926
  };
892
927
  var inMemoryReactor = (options) => {
893
- const database = _nullishCoalesce(_optionalChain([options, 'access', _59 => _59.connectionOptions, 'optionalAccess', _60 => _60.database]), () => ( getInMemoryDatabase()));
928
+ const database = _nullishCoalesce(_optionalChain([options, 'access', _62 => _62.connectionOptions, 'optionalAccess', _63 => _63.database]), () => ( getInMemoryDatabase()));
894
929
  const hooks = {
895
- onInit: _optionalChain([options, 'access', _61 => _61.hooks, 'optionalAccess', _62 => _62.onInit]),
896
- onStart: _optionalChain([options, 'access', _63 => _63.hooks, 'optionalAccess', _64 => _64.onStart]),
897
- onClose: _optionalChain([options, 'access', _65 => _65.hooks, 'optionalAccess', _66 => _66.onClose])
930
+ onInit: _optionalChain([options, 'access', _64 => _64.hooks, 'optionalAccess', _65 => _65.onInit]),
931
+ onStart: _optionalChain([options, 'access', _66 => _66.hooks, 'optionalAccess', _67 => _67.onStart]),
932
+ onClose: _optionalChain([options, 'access', _68 => _68.hooks, 'optionalAccess', _69 => _69.onClose])
898
933
  };
899
934
  const processor = reactor({
900
935
  ...options,
@@ -907,6 +942,49 @@ var inMemoryReactor = (options) => {
907
942
  });
908
943
  return Object.assign(processor, { database });
909
944
  };
945
+ var downcastRecordedMessage = (recordedMessage, options) => {
946
+ if (!_optionalChain([options, 'optionalAccess', _70 => _70.downcast]))
947
+ return recordedMessage;
948
+ const downcasted = options.downcast(
949
+ recordedMessage
950
+ );
951
+ return {
952
+ ...recordedMessage,
953
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
954
+ data: downcasted.data,
955
+ ..."metadata" in recordedMessage || "metadata" in downcasted ? {
956
+ metadata: {
957
+ ..."metadata" in recordedMessage ? recordedMessage.metadata : {},
958
+ ..."metadata" in downcasted ? downcasted.metadata : {}
959
+ }
960
+ } : {}
961
+ };
962
+ };
963
+ var downcastRecordedMessages = (recordedMessages, options) => {
964
+ if (!_optionalChain([options, 'optionalAccess', _71 => _71.downcast]))
965
+ return recordedMessages;
966
+ return recordedMessages.map(
967
+ (recordedMessage) => downcastRecordedMessage(recordedMessage, options)
968
+ );
969
+ };
970
+ var upcastRecordedMessage = (recordedMessage, options) => {
971
+ if (!_optionalChain([options, 'optionalAccess', _72 => _72.upcast]))
972
+ return recordedMessage;
973
+ const upcasted = options.upcast(
974
+ recordedMessage
975
+ );
976
+ return {
977
+ ...recordedMessage,
978
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
979
+ data: upcasted.data,
980
+ ..."metadata" in recordedMessage || "metadata" in upcasted ? {
981
+ metadata: {
982
+ ..."metadata" in recordedMessage ? recordedMessage.metadata : {},
983
+ ..."metadata" in upcasted ? upcasted.metadata : {}
984
+ }
985
+ } : {}
986
+ };
987
+ };
910
988
 
911
989
  // src/eventStore/consumers/eventStoreDBEventStoreConsumer.ts
912
990
 
@@ -942,7 +1020,7 @@ var getEventStoreDBEventStore = (eventStore) => {
942
1020
  return {
943
1021
  async aggregateStream(streamName, options) {
944
1022
  const { evolve, initialState, read } = options;
945
- const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _67 => _67.expectedStreamVersion]);
1023
+ const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _73 => _73.expectedStreamVersion]);
946
1024
  let state = initialState();
947
1025
  let currentStreamVersion = EventStoreDBEventStoreDefaultStreamVersion;
948
1026
  let lastEventGlobalPosition = void 0;
@@ -957,11 +1035,11 @@ var getEventStoreDBEventStore = (eventStore) => {
957
1035
  state,
958
1036
  upcastRecordedMessage(
959
1037
  mapFromESDBEvent(resolvedEvent),
960
- _optionalChain([options, 'optionalAccess', _68 => _68.read, 'optionalAccess', _69 => _69.schema, 'optionalAccess', _70 => _70.versioning])
1038
+ _optionalChain([options, 'optionalAccess', _74 => _74.read, 'optionalAccess', _75 => _75.schema, 'optionalAccess', _76 => _76.versioning])
961
1039
  )
962
1040
  );
963
1041
  currentStreamVersion = event.revision;
964
- lastEventGlobalPosition = _optionalChain([event, 'access', _71 => _71.position, 'optionalAccess', _72 => _72.commit]);
1042
+ lastEventGlobalPosition = _optionalChain([event, 'access', _77 => _77.position, 'optionalAccess', _78 => _78.commit]);
965
1043
  }
966
1044
  assertExpectedVersionMatchesCurrent(
967
1045
  currentStreamVersion,
@@ -1002,7 +1080,7 @@ var getEventStoreDBEventStore = (eventStore) => {
1002
1080
  events.push(
1003
1081
  upcastRecordedMessage(
1004
1082
  mapFromESDBEvent(resolvedEvent),
1005
- _optionalChain([options, 'optionalAccess', _73 => _73.schema, 'optionalAccess', _74 => _74.versioning])
1083
+ _optionalChain([options, 'optionalAccess', _79 => _79.schema, 'optionalAccess', _80 => _80.versioning])
1006
1084
  )
1007
1085
  );
1008
1086
  currentStreamVersion = event.revision;
@@ -1027,11 +1105,11 @@ var getEventStoreDBEventStore = (eventStore) => {
1027
1105
  try {
1028
1106
  const eventsToStore = downcastRecordedMessages(
1029
1107
  events,
1030
- _optionalChain([options, 'optionalAccess', _75 => _75.schema, 'optionalAccess', _76 => _76.versioning])
1108
+ _optionalChain([options, 'optionalAccess', _81 => _81.schema, 'optionalAccess', _82 => _82.versioning])
1031
1109
  );
1032
1110
  const serializedEvents = eventsToStore.map(_dbclient.jsonEvent);
1033
1111
  const expectedRevision = toExpectedRevision(
1034
- _optionalChain([options, 'optionalAccess', _77 => _77.expectedStreamVersion])
1112
+ _optionalChain([options, 'optionalAccess', _83 => _83.expectedStreamVersion])
1035
1113
  );
1036
1114
  const appendResult = await eventStore.appendToStream(
1037
1115
  streamName,
@@ -1048,7 +1126,7 @@ var getEventStoreDBEventStore = (eventStore) => {
1048
1126
  } catch (error) {
1049
1127
  if (error instanceof _dbclient.WrongExpectedVersionError) {
1050
1128
  throw new ExpectedVersionConflictError(
1051
- error.actualVersion,
1129
+ BigInt(error.actualVersion),
1052
1130
  toExpectedVersion(error.expectedVersion)
1053
1131
  );
1054
1132
  }
@@ -1077,8 +1155,8 @@ var getEventStoreDBEventStore = (eventStore) => {
1077
1155
  //streamEvents: streamEvents(eventStore),
1078
1156
  };
1079
1157
  };
1080
- var getCheckpoint2 = (resolvedEvent, from) => {
1081
- return !from || _optionalChain([from, 'optionalAccess', _78 => _78.stream]) === $all ? _nullishCoalesce(_optionalChain([resolvedEvent, 'access', _79 => _79.link, 'optionalAccess', _80 => _80.position, 'optionalAccess', _81 => _81.commit]), () => ( _optionalChain([resolvedEvent, 'access', _82 => _82.event, 'optionalAccess', _83 => _83.position, 'optionalAccess', _84 => _84.commit]))) : _nullishCoalesce(_optionalChain([resolvedEvent, 'access', _85 => _85.link, 'optionalAccess', _86 => _86.revision]), () => ( resolvedEvent.event.revision));
1158
+ var getESDBCheckpoint = (resolvedEvent, from) => {
1159
+ return !from || _optionalChain([from, 'optionalAccess', _84 => _84.stream]) === $all ? _nullishCoalesce(_optionalChain([resolvedEvent, 'access', _85 => _85.link, 'optionalAccess', _86 => _86.position, 'optionalAccess', _87 => _87.commit]), () => ( _optionalChain([resolvedEvent, 'access', _88 => _88.event, 'optionalAccess', _89 => _89.position, 'optionalAccess', _90 => _90.commit]))) : _nullishCoalesce(_optionalChain([resolvedEvent, 'access', _91 => _91.link, 'optionalAccess', _92 => _92.revision]), () => ( resolvedEvent.event.revision));
1082
1160
  };
1083
1161
  var mapFromESDBEvent = (resolvedEvent, from) => {
1084
1162
  const event = resolvedEvent.event;
@@ -1091,7 +1169,9 @@ var mapFromESDBEvent = (resolvedEvent, from) => {
1091
1169
  streamName: event.streamId,
1092
1170
  streamPosition: event.revision,
1093
1171
  globalPosition: event.position.commit,
1094
- checkpoint: getCheckpoint2(resolvedEvent, from)
1172
+ checkpoint: bigIntProcessorCheckpoint(
1173
+ getESDBCheckpoint(resolvedEvent, from)
1174
+ )
1095
1175
  }
1096
1176
  };
1097
1177
  };
@@ -1114,12 +1194,12 @@ var toExpectedVersion = (expected) => {
1114
1194
  var DefaultEventStoreDBEventStoreProcessorBatchSize = 100;
1115
1195
  var DefaultEventStoreDBEventStoreProcessorPullingFrequencyInMs = 50;
1116
1196
  var toGlobalPosition = (startFrom) => startFrom === "BEGINNING" ? _dbclient.START : startFrom === "END" ? _dbclient.END : {
1117
- prepare: startFrom.lastCheckpoint,
1118
- commit: startFrom.lastCheckpoint
1197
+ prepare: parseBigIntProcessorCheckpoint(startFrom.lastCheckpoint),
1198
+ commit: parseBigIntProcessorCheckpoint(startFrom.lastCheckpoint)
1119
1199
  };
1120
- var toStreamPosition = (startFrom) => startFrom === "BEGINNING" ? _dbclient.START : startFrom === "END" ? _dbclient.END : startFrom.lastCheckpoint;
1200
+ var toStreamPosition = (startFrom) => startFrom === "BEGINNING" ? _dbclient.START : startFrom === "END" ? _dbclient.END : parseBigIntProcessorCheckpoint(startFrom.lastCheckpoint);
1121
1201
  var subscribe = (client, from, options) => from == void 0 || from.stream == $all ? client.subscribeToAll({
1122
- ..._nullishCoalesce(_optionalChain([from, 'optionalAccess', _87 => _87.options]), () => ( {})),
1202
+ ..._nullishCoalesce(_optionalChain([from, 'optionalAccess', _93 => _93.options]), () => ( {})),
1123
1203
  fromPosition: toGlobalPosition(options.startFrom),
1124
1204
  filter: _dbclient.excludeSystemEvents.call(void 0, )
1125
1205
  }) : client.subscribeToStream(from.stream, {
@@ -1178,7 +1258,7 @@ var eventStoreDBSubscription = ({
1178
1258
  let start;
1179
1259
  let processor;
1180
1260
  let subscription;
1181
- const resubscribeOptions = _nullishCoalesce(_optionalChain([resilience, 'optionalAccess', _88 => _88.resubscribeOptions]), () => ( {
1261
+ const resubscribeOptions = _nullishCoalesce(_optionalChain([resilience, 'optionalAccess', _94 => _94.resubscribeOptions]), () => ( {
1182
1262
  ...EventStoreDBResubscribeDefaultOptions,
1183
1263
  shouldRetryResult: () => isRunning,
1184
1264
  shouldRetryError: (error) => isRunning && EventStoreDBResubscribeDefaultOptions.shouldRetryError(error)
@@ -1200,7 +1280,7 @@ var eventStoreDBSubscription = ({
1200
1280
  return;
1201
1281
  }
1202
1282
  console.info(
1203
- `Starting subscription. ${retry2++} retries. From: ${JSONParser.stringify(_nullishCoalesce(from, () => ( "$all")))}, Start from: ${JSONParser.stringify(
1283
+ `Starting subscription. ${retry2++} retries. From: ${JSONSerializer.serialize(_nullishCoalesce(from, () => ( "$all")))}, Start from: ${JSONSerializer.serialize(
1204
1284
  options.startFrom
1205
1285
  )}`
1206
1286
  );
@@ -1215,7 +1295,7 @@ var eventStoreDBSubscription = ({
1215
1295
  const handler = new class extends _stream.Writable {
1216
1296
  async _write(result, _encoding, done) {
1217
1297
  if (!isRunning) return;
1218
- if (isBigint(result)) {
1298
+ if (isString(result)) {
1219
1299
  options.startFrom = {
1220
1300
  lastCheckpoint: result
1221
1301
  };
@@ -1244,7 +1324,7 @@ var eventStoreDBSubscription = ({
1244
1324
  return;
1245
1325
  }
1246
1326
  console.error(
1247
- `Received error: ${JSONParser.stringify(error)}.`
1327
+ `Received error: ${JSONSerializer.serialize(error)}.`
1248
1328
  );
1249
1329
  reject(error);
1250
1330
  });
@@ -1301,9 +1381,9 @@ var eventStoreDBEventStoreConsumer = (options) => {
1301
1381
  return await s.handle(messagesBatch, { client });
1302
1382
  })
1303
1383
  );
1304
- const error = _optionalChain([result, 'access', _89 => _89.find, 'call', _90 => _90((r) => r.status === "rejected"), 'optionalAccess', _91 => _91.reason]);
1384
+ const error = _optionalChain([result, 'access', _95 => _95.find, 'call', _96 => _96((r) => r.status === "rejected"), 'optionalAccess', _97 => _97.reason]);
1305
1385
  return result.some(
1306
- (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _92 => _92.value, 'optionalAccess', _93 => _93.type]) !== "STOP"
1386
+ (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _98 => _98.value, 'optionalAccess', _99 => _99.type]) !== "STOP"
1307
1387
  ) ? void 0 : {
1308
1388
  type: "STOP",
1309
1389
  error: error ? EmmettError.mapFrom(error) : void 0
@@ -1313,7 +1393,7 @@ var eventStoreDBEventStoreConsumer = (options) => {
1313
1393
  client,
1314
1394
  from: options.from,
1315
1395
  eachBatch,
1316
- batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _94 => _94.batchSize]), () => ( DefaultEventStoreDBEventStoreProcessorBatchSize)),
1396
+ batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _100 => _100.batchSize]), () => ( DefaultEventStoreDBEventStoreProcessorBatchSize)),
1317
1397
  resilience: options.resilience
1318
1398
  });
1319
1399
  const stop = async () => {