@event-driven-io/emmett-sqlite 0.43.0-beta.11 → 0.43.0-beta.13

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,131 +1,4 @@
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(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await 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;// src/eventStore/projections/pongo/pongoProjections.ts
2
-
3
-
4
- var _pongo = require('@event-driven-io/pongo');
5
- var pongoProjection = ({
6
- name,
7
- kind,
8
- version,
9
- truncate,
10
- handle,
11
- canHandle,
12
- eventsOptions
13
- }) => sqliteProjection({
14
- name,
15
- version,
16
- kind: _nullishCoalesce(kind, () => ( "emt:projections:postgresql:pongo:generic")),
17
- canHandle,
18
- eventsOptions,
19
- handle: async (events, context) => {
20
- const { connection } = context;
21
- const driver = await pongoDriverRegistry.tryResolve(
22
- context.driverType
23
- );
24
- const pongo = _pongo.pongoClient.call(void 0, {
25
- driver,
26
- connectionOptions: { connection }
27
- });
28
- try {
29
- await handle(events, {
30
- ...context,
31
- pongo
32
- });
33
- } finally {
34
- await pongo.close();
35
- }
36
- },
37
- truncate: truncate ? async (context) => {
38
- const { connection } = context;
39
- const driver = await pongoDriverRegistry.tryResolve(
40
- context.driverType
41
- );
42
- const pongo = _pongo.pongoClient.call(void 0, {
43
- driver,
44
- connectionOptions: { connection }
45
- });
46
- try {
47
- await truncate({
48
- ...context,
49
- pongo
50
- });
51
- } finally {
52
- await pongo.close();
53
- }
54
- } : void 0
55
- });
56
- var pongoMultiStreamProjection = (options) => {
57
- const { collectionName, getDocumentId, canHandle } = options;
58
- const collectionNameWithVersion = options.version && options.version > 0 ? `${collectionName}_v${options.version}` : collectionName;
59
- return pongoProjection({
60
- name: collectionNameWithVersion,
61
- version: options.version,
62
- kind: _nullishCoalesce(options.kind, () => ( "emt:projections:postgresql:pongo:multi_stream")),
63
- eventsOptions: options.eventsOptions,
64
- handle: async (events, { pongo }) => {
65
- const collection = pongo.db().collection(
66
- collectionNameWithVersion,
67
- options.collectionOptions
68
- );
69
- for (const event of events) {
70
- await collection.handle(getDocumentId(event), async (document) => {
71
- return "initialState" in options ? await options.evolve(
72
- _nullishCoalesce(document, () => ( options.initialState())),
73
- event
74
- ) : await options.evolve(
75
- document,
76
- event
77
- );
78
- });
79
- }
80
- },
81
- canHandle,
82
- truncate: async (context) => {
83
- const { connection } = context;
84
- const driver = await pongoDriverRegistry.tryResolve(
85
- context.driverType
86
- );
87
- const pongo = _pongo.pongoClient.call(void 0, {
88
- driver,
89
- connectionOptions: { connection }
90
- });
91
- try {
92
- await pongo.db().collection(
93
- collectionNameWithVersion,
94
- options.collectionOptions
95
- ).deleteMany();
96
- } finally {
97
- await pongo.close();
98
- }
99
- },
100
- init: async (context) => {
101
- const { connection } = context;
102
- const driver = await pongoDriverRegistry.tryResolve(
103
- context.driverType
104
- );
105
- const pongo = _pongo.pongoClient.call(void 0, {
106
- connectionOptions: { connection },
107
- driver
108
- });
109
- try {
110
- await pongo.db().collection(
111
- collectionNameWithVersion,
112
- options.collectionOptions
113
- ).schema.migrate();
114
- } finally {
115
- await pongo.close();
116
- }
117
- }
118
- });
119
- };
120
- var pongoSingleStreamProjection = (options) => {
121
- return pongoMultiStreamProjection({
122
- ...options,
123
- kind: "emt:projections:postgresql:pongo:single_stream",
124
- getDocumentId: _nullishCoalesce(options.getDocumentId, () => ( ((event) => event.metadata.streamName)))
125
- });
126
- };
127
-
128
- // ../emmett/dist/chunk-AZDDB5SF.js
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(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await 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
129
2
  var isNumber = (val) => typeof val === "number" && val === val;
130
3
  var isString = (val) => typeof val === "string";
131
4
  var isErrorConstructor = (expect) => {
@@ -218,6 +91,13 @@ var isExpectedVersionConflictError = (error) => error instanceof ExpectedVersion
218
91
  error,
219
92
  ExpectedVersionConflictError.Codes.ConcurrencyError
220
93
  );
94
+ async function reduceAsync(items, fn, initial) {
95
+ let accumulator = initial;
96
+ for (let i = 0; i < items.length; i++) {
97
+ accumulator = await fn(accumulator, items[i], i);
98
+ }
99
+ return accumulator;
100
+ }
221
101
  var isPrimitive = (value) => {
222
102
  const type = typeof value;
223
103
  return value === null || value === void 0 || type === "boolean" || type === "number" || type === "string" || type === "symbol" || type === "bigint";
@@ -609,7 +489,40 @@ var reactor = (options) => {
609
489
  canHandle,
610
490
  stopAfter
611
491
  } = options;
612
- const eachMessage = "eachMessage" in options && options.eachMessage ? options.eachMessage : () => Promise.resolve();
492
+ const isCustomBatch = "eachBatch" in options && !!options.eachBatch;
493
+ const eachBatch = isCustomBatch ? options.eachBatch : async (messages, context) => {
494
+ let result = void 0;
495
+ for (let i = 0; i < messages.length; i++) {
496
+ const message2 = messages[i];
497
+ const messageProcessingResult = await options.eachMessage(
498
+ message2,
499
+ context
500
+ );
501
+ if (messageProcessingResult && messageProcessingResult.type === "STOP") {
502
+ result = {
503
+ ...messageProcessingResult,
504
+ lastSuccessfulMessage: messageProcessingResult.error ? messages[i - 1] : message2
505
+ };
506
+ break;
507
+ }
508
+ if (stopAfter && stopAfter(message2)) {
509
+ result = {
510
+ type: "STOP",
511
+ reason: "Stop condition reached",
512
+ lastSuccessfulMessage: message2
513
+ };
514
+ break;
515
+ }
516
+ if (messageProcessingResult && messageProcessingResult.type === "SKIP") {
517
+ result = {
518
+ ...messageProcessingResult,
519
+ lastSuccessfulMessage: message2
520
+ };
521
+ continue;
522
+ }
523
+ }
524
+ return result;
525
+ };
613
526
  let isInitiated = false;
614
527
  let isActive = false;
615
528
  let lastCheckpoint = null;
@@ -647,10 +560,11 @@ var reactor = (options) => {
647
560
  await init(startOptions);
648
561
  isActive = true;
649
562
  closeSignal = onShutdown(() => close(startOptions));
650
- if (lastCheckpoint !== null)
563
+ if (lastCheckpoint !== null) {
651
564
  return {
652
565
  lastCheckpoint
653
566
  };
567
+ }
654
568
  return await processingScope(async (context) => {
655
569
  if (hooks.onStart) {
656
570
  await hooks.onStart(context);
@@ -679,46 +593,48 @@ var reactor = (options) => {
679
593
  handle: async (messages, partialContext) => {
680
594
  if (!isActive) return Promise.resolve();
681
595
  return await processingScope(async (context) => {
682
- let result = void 0;
683
- for (const message2 of messages) {
684
- if (wasMessageHandled(message2, lastCheckpoint)) continue;
685
- const upcasted = upcastRecordedMessage(
596
+ const messagesAboveCheckpoint = messages.filter(
597
+ (message2) => !wasMessageHandled(message2, lastCheckpoint)
598
+ );
599
+ const upcastedMessages = messagesAboveCheckpoint.map(
600
+ (message2) => upcastRecordedMessage(
686
601
  // TODO: Make it smarter
687
602
  message2,
688
603
  _optionalChain([options, 'access', _24 => _24.messageOptions, 'optionalAccess', _25 => _25.schema, 'optionalAccess', _26 => _26.versioning])
604
+ )
605
+ ).filter(
606
+ (upcasted) => !canHandle || canHandle.includes(upcasted.type)
607
+ );
608
+ const stopMessageIndex = isCustomBatch && stopAfter ? upcastedMessages.findIndex(stopAfter) : -1;
609
+ const unhandledMessages = stopMessageIndex !== -1 ? upcastedMessages.slice(0, stopMessageIndex + 1) : upcastedMessages;
610
+ const batchResult = await eachBatch(unhandledMessages, context);
611
+ const messageProcessingResult = _optionalChain([batchResult, 'optionalAccess', _27 => _27.type]) === "STOP" ? batchResult : stopMessageIndex !== -1 ? {
612
+ type: "STOP",
613
+ reason: "Stop condition reached",
614
+ lastSuccessfulMessage: unhandledMessages[stopMessageIndex]
615
+ } : batchResult;
616
+ const isStop = messageProcessingResult && messageProcessingResult.type === "STOP";
617
+ const checkpointMessage = _optionalChain([messageProcessingResult, 'optionalAccess', _28 => _28.type]) === "STOP" ? messageProcessingResult.lastSuccessfulMessage : messagesAboveCheckpoint[messagesAboveCheckpoint.length - 1];
618
+ if (checkpointMessage && checkpoints) {
619
+ const storeCheckpointResult = await checkpoints.store(
620
+ {
621
+ processorId,
622
+ version,
623
+ message: checkpointMessage,
624
+ lastCheckpoint,
625
+ partition
626
+ },
627
+ context
689
628
  );
690
- if (canHandle !== void 0 && !canHandle.includes(upcasted.type))
691
- continue;
692
- const messageProcessingResult = await eachMessage(upcasted, context);
693
- if (checkpoints) {
694
- const storeCheckpointResult = await checkpoints.store(
695
- {
696
- processorId,
697
- version,
698
- message: upcasted,
699
- lastCheckpoint,
700
- partition
701
- },
702
- context
703
- );
704
- if (storeCheckpointResult.success) {
705
- lastCheckpoint = storeCheckpointResult.newCheckpoint;
706
- }
707
- }
708
- if (messageProcessingResult && messageProcessingResult.type === "STOP") {
709
- isActive = false;
710
- result = messageProcessingResult;
711
- break;
712
- }
713
- if (stopAfter && stopAfter(upcasted)) {
714
- isActive = false;
715
- result = { type: "STOP", reason: "Stop condition reached" };
716
- break;
629
+ if (storeCheckpointResult.success) {
630
+ lastCheckpoint = storeCheckpointResult.newCheckpoint;
717
631
  }
718
- if (messageProcessingResult && messageProcessingResult.type === "SKIP")
719
- continue;
720
632
  }
721
- return result;
633
+ if (isStop) {
634
+ isActive = false;
635
+ return messageProcessingResult;
636
+ }
637
+ return void 0;
722
638
  }, partialContext);
723
639
  }
724
640
  };
@@ -738,15 +654,15 @@ var projector = (options) => {
738
654
  processorId,
739
655
  messageOptions: options.projection.eventsOptions,
740
656
  hooks: {
741
- onInit: _optionalChain([options, 'access', _27 => _27.hooks, 'optionalAccess', _28 => _28.onInit]),
742
- onStart: options.truncateOnStart && options.projection.truncate || _optionalChain([options, 'access', _29 => _29.hooks, 'optionalAccess', _30 => _30.onStart]) ? async (context) => {
657
+ onInit: _optionalChain([options, 'access', _29 => _29.hooks, 'optionalAccess', _30 => _30.onInit]),
658
+ onStart: options.truncateOnStart && options.projection.truncate || _optionalChain([options, 'access', _31 => _31.hooks, 'optionalAccess', _32 => _32.onStart]) ? async (context) => {
743
659
  if (options.truncateOnStart && options.projection.truncate)
744
660
  await options.projection.truncate(context);
745
- if (_optionalChain([options, 'access', _31 => _31.hooks, 'optionalAccess', _32 => _32.onStart])) await _optionalChain([options, 'access', _33 => _33.hooks, 'optionalAccess', _34 => _34.onStart, 'call', _35 => _35(context)]);
661
+ if (_optionalChain([options, 'access', _33 => _33.hooks, 'optionalAccess', _34 => _34.onStart])) await _optionalChain([options, 'access', _35 => _35.hooks, 'optionalAccess', _36 => _36.onStart, 'call', _37 => _37(context)]);
746
662
  } : void 0,
747
- onClose: _optionalChain([options, 'access', _36 => _36.hooks, 'optionalAccess', _37 => _37.onClose])
663
+ onClose: _optionalChain([options, 'access', _38 => _38.hooks, 'optionalAccess', _39 => _39.onClose])
748
664
  },
749
- eachMessage: async (event2, context) => projection2.handle([event2], context)
665
+ eachBatch: async (events, context) => projection2.handle(events, context)
750
666
  });
751
667
  };
752
668
  var AssertionError = class extends Error {
@@ -868,7 +784,7 @@ var assertThatArray = (array) => {
868
784
  };
869
785
  };
870
786
  var downcastRecordedMessage = (recordedMessage, options) => {
871
- if (!_optionalChain([options, 'optionalAccess', _38 => _38.downcast]))
787
+ if (!_optionalChain([options, 'optionalAccess', _40 => _40.downcast]))
872
788
  return recordedMessage;
873
789
  const downcasted = options.downcast(
874
790
  recordedMessage
@@ -886,14 +802,14 @@ var downcastRecordedMessage = (recordedMessage, options) => {
886
802
  };
887
803
  };
888
804
  var downcastRecordedMessages = (recordedMessages, options) => {
889
- if (!_optionalChain([options, 'optionalAccess', _39 => _39.downcast]))
805
+ if (!_optionalChain([options, 'optionalAccess', _41 => _41.downcast]))
890
806
  return recordedMessages;
891
807
  return recordedMessages.map(
892
808
  (recordedMessage) => downcastRecordedMessage(recordedMessage, options)
893
809
  );
894
810
  };
895
811
  var upcastRecordedMessage = (recordedMessage, options) => {
896
- if (!_optionalChain([options, 'optionalAccess', _40 => _40.upcast]))
812
+ if (!_optionalChain([options, 'optionalAccess', _42 => _42.upcast]))
897
813
  return recordedMessage;
898
814
  const upcasted = options.upcast(
899
815
  recordedMessage
@@ -961,11 +877,11 @@ var createWrappedEvolve = (evolve, workflowName, separateInputInboxFromProcessin
961
877
  return (state, event2) => {
962
878
  const metadata = event2.metadata;
963
879
  let processedInputIds = state.processedInputIds;
964
- if (_optionalChain([metadata, 'optionalAccess', _41 => _41.input]) === true && typeof _optionalChain([metadata, 'optionalAccess', _42 => _42.originalMessageId]) === "string") {
880
+ if (_optionalChain([metadata, 'optionalAccess', _43 => _43.input]) === true && typeof _optionalChain([metadata, 'optionalAccess', _44 => _44.originalMessageId]) === "string") {
965
881
  processedInputIds = new Set(state.processedInputIds);
966
882
  processedInputIds.add(metadata.originalMessageId);
967
883
  }
968
- if (separateInputInboxFromProcessing && _optionalChain([metadata, 'optionalAccess', _43 => _43.input]) === true) {
884
+ if (separateInputInboxFromProcessing && _optionalChain([metadata, 'optionalAccess', _45 => _45.input]) === true) {
969
885
  return {
970
886
  userState: state.userState,
971
887
  processedInputIds
@@ -995,7 +911,7 @@ var WorkflowHandler = (options) => async (store, message2, handleOptions) => asy
995
911
  } = options;
996
912
  const inputMessageId = (
997
913
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
998
- _nullishCoalesce(("metadata" in message2 && _optionalChain([message2, 'access', _44 => _44.metadata, 'optionalAccess', _45 => _45.messageId]) ? (
914
+ _nullishCoalesce(("metadata" in message2 && _optionalChain([message2, 'access', _46 => _46.metadata, 'optionalAccess', _47 => _47.messageId]) ? (
999
915
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1000
916
  message2.metadata.messageId
1001
917
  ) : void 0), () => ( _uuid.v7.call(void 0, )))
@@ -1031,7 +947,7 @@ var WorkflowHandler = (options) => async (store, message2, handleOptions) => asy
1031
947
  [inputToStore2],
1032
948
  {
1033
949
  ...handleOptions,
1034
- expectedStreamVersion: _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _46 => _46.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
950
+ expectedStreamVersion: _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _48 => _48.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1035
951
  }
1036
952
  );
1037
953
  return {
@@ -1052,7 +968,7 @@ var WorkflowHandler = (options) => async (store, message2, handleOptions) => asy
1052
968
  ...handleOptions,
1053
969
  // expected stream version is passed to fail fast
1054
970
  // if stream is in the wrong state
1055
- expectedStreamVersion: _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _47 => _47.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
971
+ expectedStreamVersion: _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _49 => _49.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1056
972
  }
1057
973
  });
1058
974
  const { currentStreamVersion } = aggregationResult;
@@ -1076,7 +992,7 @@ var WorkflowHandler = (options) => async (store, message2, handleOptions) => asy
1076
992
  metadata: inputMetadata
1077
993
  };
1078
994
  const outputMessages = (Array.isArray(result2) ? result2 : [result2]).filter((msg) => msg !== void 0 && msg !== null);
1079
- const outputCommandTypes = _nullishCoalesce(_optionalChain([options, 'access', _48 => _48.outputs, 'optionalAccess', _49 => _49.commands]), () => ( []));
995
+ const outputCommandTypes = _nullishCoalesce(_optionalChain([options, 'access', _50 => _50.outputs, 'optionalAccess', _51 => _51.commands]), () => ( []));
1080
996
  const taggedOutputMessages = outputMessages.map((msg) => {
1081
997
  const action = outputCommandTypes.includes(
1082
998
  msg.type
@@ -1087,7 +1003,7 @@ var WorkflowHandler = (options) => async (store, message2, handleOptions) => asy
1087
1003
  if (messagesToAppend.length === 0) {
1088
1004
  return emptyHandlerResult(currentStreamVersion);
1089
1005
  }
1090
- const expectedStreamVersion = _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _50 => _50.expectedStreamVersion]), () => ( (aggregationResult.streamExists ? currentStreamVersion : STREAM_DOES_NOT_EXIST)));
1006
+ const expectedStreamVersion = _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _52 => _52.expectedStreamVersion]), () => ( (aggregationResult.streamExists ? currentStreamVersion : STREAM_DOES_NOT_EXIST)));
1091
1007
  const appendResult = await eventStore.appendToStream(
1092
1008
  streamName,
1093
1009
  // TODO: Fix this cast
@@ -1134,7 +1050,7 @@ var workflowProcessor = (options) => {
1134
1050
  eachMessage: async (message2, context) => {
1135
1051
  const messageType = message2.type;
1136
1052
  const metadata = message2.metadata;
1137
- const isInput = _optionalChain([metadata, 'optionalAccess', _51 => _51.input]) === true;
1053
+ const isInput = _optionalChain([metadata, 'optionalAccess', _53 => _53.input]) === true;
1138
1054
  if (isInput || inputs.includes(messageType)) {
1139
1055
  const result = await handle(
1140
1056
  context.connection.messageStore,
@@ -1152,11 +1068,9 @@ var workflowProcessor = (options) => {
1152
1068
  }
1153
1069
  return;
1154
1070
  }
1155
- if (_optionalChain([options, 'access', _52 => _52.outputHandler, 'optionalAccess', _53 => _53.canHandle, 'access', _54 => _54.includes, 'call', _55 => _55(messageType)]) === true) {
1156
- const handledOutputMessages = await options.outputHandler.handle(
1157
- message2,
1158
- context
1159
- );
1071
+ if (_optionalChain([options, 'access', _54 => _54.outputHandler, 'optionalAccess', _55 => _55.canHandle, 'access', _56 => _56.includes, 'call', _57 => _57(messageType)]) === true) {
1072
+ const recordedMessage = message2;
1073
+ const handledOutputMessages = options.outputHandler.eachBatch ? await options.outputHandler.eachBatch([recordedMessage], context) : await options.outputHandler.eachMessage(recordedMessage, context);
1160
1074
  if (handledOutputMessages instanceof EmmettError) {
1161
1075
  return {
1162
1076
  type: "STOP",
@@ -1187,6 +1101,146 @@ var workflowProcessor = (options) => {
1187
1101
  });
1188
1102
  };
1189
1103
 
1104
+ // src/eventStore/projections/pongo/pongoProjections.ts
1105
+
1106
+
1107
+ var _pongo = require('@event-driven-io/pongo');
1108
+ var pongoProjection = ({
1109
+ name,
1110
+ kind,
1111
+ version,
1112
+ truncate,
1113
+ handle,
1114
+ canHandle,
1115
+ eventsOptions
1116
+ }) => sqliteProjection({
1117
+ name,
1118
+ version,
1119
+ kind: _nullishCoalesce(kind, () => ( "emt:projections:postgresql:pongo:generic")),
1120
+ canHandle,
1121
+ eventsOptions,
1122
+ handle: async (events, context) => {
1123
+ const { connection } = context;
1124
+ const driver = await pongoDriverRegistry.tryResolve(
1125
+ context.driverType
1126
+ );
1127
+ const pongo = _pongo.pongoClient.call(void 0, {
1128
+ driver,
1129
+ connectionOptions: { connection }
1130
+ });
1131
+ try {
1132
+ await handle(events, {
1133
+ ...context,
1134
+ pongo
1135
+ });
1136
+ } finally {
1137
+ await pongo.close();
1138
+ }
1139
+ },
1140
+ truncate: truncate ? async (context) => {
1141
+ const { connection } = context;
1142
+ const driver = await pongoDriverRegistry.tryResolve(
1143
+ context.driverType
1144
+ );
1145
+ const pongo = _pongo.pongoClient.call(void 0, {
1146
+ driver,
1147
+ connectionOptions: { connection }
1148
+ });
1149
+ try {
1150
+ await truncate({
1151
+ ...context,
1152
+ pongo
1153
+ });
1154
+ } finally {
1155
+ await pongo.close();
1156
+ }
1157
+ } : void 0
1158
+ });
1159
+ var pongoMultiStreamProjection = (options) => {
1160
+ const { collectionName, getDocumentId, canHandle } = options;
1161
+ const collectionNameWithVersion = options.version && options.version > 0 ? `${collectionName}_v${options.version}` : collectionName;
1162
+ return pongoProjection({
1163
+ name: collectionNameWithVersion,
1164
+ version: options.version,
1165
+ kind: _nullishCoalesce(options.kind, () => ( "emt:projections:postgresql:pongo:multi_stream")),
1166
+ eventsOptions: options.eventsOptions,
1167
+ handle: async (events, { pongo }) => {
1168
+ const collection = pongo.db().collection(
1169
+ collectionNameWithVersion,
1170
+ options.collectionOptions
1171
+ );
1172
+ const eventsByDocumentId = events.map((event) => {
1173
+ const documentId = getDocumentId(event);
1174
+ return {
1175
+ documentId,
1176
+ event
1177
+ };
1178
+ }).reduce((acc, { documentId, event }) => {
1179
+ if (!acc.has(documentId)) {
1180
+ acc.set(documentId, []);
1181
+ }
1182
+ acc.get(documentId).push(event);
1183
+ return acc;
1184
+ }, /* @__PURE__ */ new Map());
1185
+ await collection.handle(
1186
+ [...eventsByDocumentId.keys()],
1187
+ (document, id) => {
1188
+ const events2 = eventsByDocumentId.get(id);
1189
+ return reduceAsync(
1190
+ events2,
1191
+ async (acc, event) => await options.evolve(acc, event),
1192
+ _nullishCoalesce(document, () => ( ("initialState" in options ? options.initialState() : null)))
1193
+ );
1194
+ }
1195
+ );
1196
+ },
1197
+ canHandle,
1198
+ truncate: async (context) => {
1199
+ const { connection } = context;
1200
+ const driver = await pongoDriverRegistry.tryResolve(
1201
+ context.driverType
1202
+ );
1203
+ const pongo = _pongo.pongoClient.call(void 0, {
1204
+ driver,
1205
+ connectionOptions: { connection }
1206
+ });
1207
+ try {
1208
+ await pongo.db().collection(
1209
+ collectionNameWithVersion,
1210
+ options.collectionOptions
1211
+ ).deleteMany();
1212
+ } finally {
1213
+ await pongo.close();
1214
+ }
1215
+ },
1216
+ init: async (context) => {
1217
+ const { connection } = context;
1218
+ const driver = await pongoDriverRegistry.tryResolve(
1219
+ context.driverType
1220
+ );
1221
+ const pongo = _pongo.pongoClient.call(void 0, {
1222
+ connectionOptions: { connection },
1223
+ driver
1224
+ });
1225
+ try {
1226
+ await pongo.db().collection(
1227
+ collectionNameWithVersion,
1228
+ options.collectionOptions
1229
+ ).schema.migrate();
1230
+ } finally {
1231
+ await pongo.close();
1232
+ }
1233
+ }
1234
+ });
1235
+ };
1236
+ var pongoSingleStreamProjection = (options) => {
1237
+ return pongoMultiStreamProjection({
1238
+ ...options,
1239
+ kind: "emt:projections:postgresql:pongo:single_stream",
1240
+ getDocumentId: _nullishCoalesce(options.getDocumentId, () => ( ((event) => event.metadata.streamName)))
1241
+ });
1242
+ };
1243
+
1190
1244
  // src/eventStore/projections/pongo/pongoProjectionSpec.ts
1191
1245
 
1192
1246
 
@@ -1410,7 +1464,7 @@ var SQLiteProjectionSpec = {
1410
1464
  const allEvents = [];
1411
1465
  const run = async (connection) => {
1412
1466
  let globalPosition = 0n;
1413
- const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _56 => _56.numberOfTimes]), () => ( 1));
1467
+ const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _58 => _58.numberOfTimes]), () => ( 1));
1414
1468
  for (const event of [
1415
1469
  ...givenEvents,
1416
1470
  ...Array.from({ length: numberOfTimes }).flatMap(() => events)
@@ -1477,18 +1531,18 @@ var SQLiteProjectionSpec = {
1477
1531
  if (!isErrorConstructor(args[0])) {
1478
1532
  assertTrue(
1479
1533
  args[0](error),
1480
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _57 => _57.toString, 'call', _58 => _58()])}`
1534
+ `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _59 => _59.toString, 'call', _60 => _60()])}`
1481
1535
  );
1482
1536
  return;
1483
1537
  }
1484
1538
  assertTrue(
1485
1539
  error instanceof args[0],
1486
- `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _59 => _59.toString, 'call', _60 => _60()])}`
1540
+ `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _61 => _61.toString, 'call', _62 => _62()])}`
1487
1541
  );
1488
1542
  if (args[1]) {
1489
1543
  assertTrue(
1490
1544
  args[1](error),
1491
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _61 => _61.toString, 'call', _62 => _62()])}`
1545
+ `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _63 => _63.toString, 'call', _64 => _64()])}`
1492
1546
  );
1493
1547
  }
1494
1548
  }
@@ -1505,7 +1559,7 @@ var eventInStream = (streamName, event) => {
1505
1559
  ...event,
1506
1560
  metadata: {
1507
1561
  ..._nullishCoalesce(event.metadata, () => ( {})),
1508
- streamName: _nullishCoalesce(_optionalChain([event, 'access', _63 => _63.metadata, 'optionalAccess', _64 => _64.streamName]), () => ( streamName))
1562
+ streamName: _nullishCoalesce(_optionalChain([event, 'access', _65 => _65.metadata, 'optionalAccess', _66 => _66.streamName]), () => ( streamName))
1509
1563
  }
1510
1564
  };
1511
1565
  };
@@ -1577,7 +1631,7 @@ var { identifier, merge } = _dumbo.SQL;
1577
1631
  var appendToStream = async (connection, streamName, streamType, messages, options) => {
1578
1632
  if (messages.length === 0) return { success: false };
1579
1633
  const expectedStreamVersion = toExpectedVersion(
1580
- _optionalChain([options, 'optionalAccess', _65 => _65.expectedStreamVersion])
1634
+ _optionalChain([options, 'optionalAccess', _67 => _67.expectedStreamVersion])
1581
1635
  );
1582
1636
  const messagesToAppend = messages.map(
1583
1637
  (m, i) => ({
@@ -1600,13 +1654,13 @@ var appendToStream = async (connection, streamName, streamType, messages, option
1600
1654
  streamType,
1601
1655
  downcastRecordedMessages(
1602
1656
  messagesToAppend,
1603
- _optionalChain([options, 'optionalAccess', _66 => _66.schema, 'optionalAccess', _67 => _67.versioning])
1657
+ _optionalChain([options, 'optionalAccess', _68 => _68.schema, 'optionalAccess', _69 => _69.versioning])
1604
1658
  ),
1605
1659
  {
1606
1660
  expectedStreamVersion
1607
1661
  }
1608
1662
  );
1609
- if (_optionalChain([options, 'optionalAccess', _68 => _68.onBeforeCommit]))
1663
+ if (_optionalChain([options, 'optionalAccess', _70 => _70.onBeforeCommit]))
1610
1664
  await options.onBeforeCommit(messagesToAppend, { connection });
1611
1665
  return { success: true, result };
1612
1666
  }
@@ -1630,7 +1684,7 @@ var toExpectedVersion = (expected) => {
1630
1684
  return expected;
1631
1685
  };
1632
1686
  var appendToStreamRaw = async (execute, streamId, streamType, messages, options) => {
1633
- let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _69 => _69.expectedStreamVersion]), () => ( null));
1687
+ let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _71 => _71.expectedStreamVersion]), () => ( null));
1634
1688
  const currentStreamVersion = await getLastStreamPosition(
1635
1689
  execute,
1636
1690
  streamId,
@@ -1648,7 +1702,7 @@ var appendToStreamRaw = async (execute, streamId, streamType, messages, options)
1648
1702
  VALUES (
1649
1703
  ${streamId},
1650
1704
  ${messages.length},
1651
- ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _70 => _70.partition]), () => ( streamsTable.columns.partition))},
1705
+ ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _72 => _72.partition]), () => ( streamsTable.columns.partition))},
1652
1706
  ${streamType},
1653
1707
  '[]',
1654
1708
  false
@@ -1658,7 +1712,7 @@ var appendToStreamRaw = async (execute, streamId, streamType, messages, options)
1658
1712
  SET stream_position = stream_position + ${messages.length}
1659
1713
  WHERE stream_id = ${streamId}
1660
1714
  AND stream_position = ${expectedStreamVersion}
1661
- AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _71 => _71.partition]), () => ( streamsTable.columns.partition))}
1715
+ AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _73 => _73.partition]), () => ( streamsTable.columns.partition))}
1662
1716
  AND is_archived = false
1663
1717
  RETURNING stream_position;
1664
1718
  `;
@@ -1666,12 +1720,12 @@ var appendToStreamRaw = async (execute, streamId, streamType, messages, options)
1666
1720
  messages,
1667
1721
  expectedStreamVersion,
1668
1722
  streamId,
1669
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _72 => _72.partition, 'optionalAccess', _73 => _73.toString, 'call', _74 => _74()]), () => ( defaultTag2))
1723
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _74 => _74.partition, 'optionalAccess', _75 => _75.toString, 'call', _76 => _76()]), () => ( defaultTag2))
1670
1724
  );
1671
1725
  const results = await execute.batchCommand([streamSQL, insertSQL], { assertChanges: true });
1672
1726
  const [streamResult, messagesResult] = results;
1673
- const streamPosition = _optionalChain([streamResult, 'optionalAccess', _75 => _75.rows, 'access', _76 => _76[0], 'optionalAccess', _77 => _77.stream_position]);
1674
- const globalPosition = _optionalChain([messagesResult, 'optionalAccess', _78 => _78.rows, 'access', _79 => _79.at, 'call', _80 => _80(-1), 'optionalAccess', _81 => _81.global_position]);
1727
+ const streamPosition = _optionalChain([streamResult, 'optionalAccess', _77 => _77.rows, 'access', _78 => _78[0], 'optionalAccess', _79 => _79.stream_position]);
1728
+ const globalPosition = _optionalChain([messagesResult, 'optionalAccess', _80 => _80.rows, 'access', _81 => _81.at, 'call', _82 => _82(-1), 'optionalAccess', _83 => _83.global_position]);
1675
1729
  if (!streamPosition)
1676
1730
  throw new ExpectedVersionConflictError(0n, _nullishCoalesce(expectedStreamVersion, () => ( 0n)));
1677
1731
  if (!globalPosition) throw new Error("Could not find global position");
@@ -1687,7 +1741,7 @@ async function getLastStreamPosition(execute, streamId, expectedStreamVersion) {
1687
1741
  _dumbo.SQL`SELECT CAST(stream_position AS VARCHAR) AS stream_position FROM ${identifier(streamsTable.name)} WHERE stream_id = ${streamId}`
1688
1742
  )
1689
1743
  );
1690
- if (_optionalChain([result, 'optionalAccess', _82 => _82.stream_position]) == null) {
1744
+ if (_optionalChain([result, 'optionalAccess', _84 => _84.stream_position]) == null) {
1691
1745
  expectedStreamVersion = 0n;
1692
1746
  } else {
1693
1747
  expectedStreamVersion = BigInt(result.stream_position);
@@ -1696,7 +1750,7 @@ async function getLastStreamPosition(execute, streamId, expectedStreamVersion) {
1696
1750
  }
1697
1751
  var buildMessageInsertQuery = (messages, expectedStreamVersion, streamId, partition) => {
1698
1752
  const values = messages.map((message) => {
1699
- if (_optionalChain([message, 'access', _83 => _83.metadata, 'optionalAccess', _84 => _84.streamPosition]) == null || typeof message.metadata.streamPosition !== "bigint") {
1753
+ if (_optionalChain([message, 'access', _85 => _85.metadata, 'optionalAccess', _86 => _86.streamPosition]) == null || typeof message.metadata.streamPosition !== "bigint") {
1700
1754
  throw new Error("Stream position is required");
1701
1755
  }
1702
1756
  const streamPosition = BigInt(message.metadata.streamPosition) + BigInt(expectedStreamVersion);
@@ -1863,7 +1917,7 @@ var readLastMessageGlobalPosition = async (execute, options) => {
1863
1917
  _dumbo.SQL`
1864
1918
  SELECT global_position
1865
1919
  FROM ${identifier3(messagesTable.name)}
1866
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _85 => _85.partition]), () => ( defaultTag2))} AND is_archived = FALSE
1920
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _87 => _87.partition]), () => ( defaultTag2))} AND is_archived = FALSE
1867
1921
  ORDER BY global_position
1868
1922
  LIMIT 1`
1869
1923
  )
@@ -1888,7 +1942,7 @@ var readMessagesBatch = async (execute, options) => {
1888
1942
  execute.query(
1889
1943
  _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
1890
1944
  FROM ${identifier4(messagesTable.name)}
1891
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _86 => _86.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
1945
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _88 => _88.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
1892
1946
  ORDER BY global_position
1893
1947
  ${limitCondition}`
1894
1948
  ),
@@ -1932,7 +1986,7 @@ var readProcessorCheckpoint = async (execute, options) => {
1932
1986
  execute.query(
1933
1987
  _dumbo.SQL`SELECT last_processed_checkpoint
1934
1988
  FROM ${identifier5(processorsTable.name)}
1935
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _87 => _87.partition]), () => ( defaultTag2))} AND processor_id = ${options.processorId}
1989
+ WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _89 => _89.partition]), () => ( defaultTag2))} AND processor_id = ${options.processorId}
1936
1990
  LIMIT 1`
1937
1991
  )
1938
1992
  );
@@ -1970,7 +2024,7 @@ var sqliteEventStoreMessageBatchPuller = ({
1970
2024
  serializer
1971
2025
  };
1972
2026
  let waitTime = 100;
1973
- while (isRunning && !_optionalChain([signal, 'optionalAccess', _88 => _88.aborted])) {
2027
+ while (isRunning && !_optionalChain([signal, 'optionalAccess', _90 => _90.aborted])) {
1974
2028
  const { messages, currentGlobalPosition, areMessagesLeft } = await readMessagesBatch(executor, readMessagesOptions);
1975
2029
  if (messages.length > 0) {
1976
2030
  const result = await eachBatch(messages);
@@ -1981,7 +2035,7 @@ var sqliteEventStoreMessageBatchPuller = ({
1981
2035
  }
1982
2036
  readMessagesOptions.after = currentGlobalPosition;
1983
2037
  await new Promise((resolve) => setTimeout(resolve, waitTime));
1984
- if (_optionalChain([stopWhen, 'optionalAccess', _89 => _89.noMessagesLeft]) === true && !areMessagesLeft) {
2038
+ if (_optionalChain([stopWhen, 'optionalAccess', _91 => _91.noMessagesLeft]) === true && !areMessagesLeft) {
1985
2039
  isRunning = false;
1986
2040
  break;
1987
2041
  }
@@ -2026,7 +2080,7 @@ var zipSQLiteEventStoreMessageBatchPullerStartFrom = (options) => {
2026
2080
  var sqliteCheckpointer = () => ({
2027
2081
  read: async (options, context) => {
2028
2082
  const result = await readProcessorCheckpoint(context.execute, options);
2029
- return { lastCheckpoint: _optionalChain([result, 'optionalAccess', _90 => _90.lastProcessedCheckpoint]) };
2083
+ return { lastCheckpoint: _optionalChain([result, 'optionalAccess', _92 => _92.lastProcessedCheckpoint]) };
2030
2084
  },
2031
2085
  store: async (options, context) => {
2032
2086
  const newCheckpoint = getCheckpoint(options.message);
@@ -2044,7 +2098,7 @@ var sqliteCheckpointer = () => ({
2044
2098
  // src/eventStore/consumers/sqliteProcessor.ts
2045
2099
  var sqliteProcessingScope = () => {
2046
2100
  const processingScope = async (handler, partialContext) => {
2047
- const connection = _optionalChain([partialContext, 'optionalAccess', _91 => _91.connection]);
2101
+ const connection = _optionalChain([partialContext, 'optionalAccess', _93 => _93.connection]);
2048
2102
  if (!connection)
2049
2103
  throw new EmmettError("Connection is required in context or options");
2050
2104
  return connection.withTransaction(
@@ -2061,7 +2115,7 @@ var sqliteProcessingScope = () => {
2061
2115
  };
2062
2116
  var sqliteWorkflowProcessingScope = (messageStore) => {
2063
2117
  const processingScope = async (handler, partialContext) => {
2064
- const connection = _optionalChain([partialContext, 'optionalAccess', _92 => _92.connection]);
2118
+ const connection = _optionalChain([partialContext, 'optionalAccess', _94 => _94.connection]);
2065
2119
  if (!connection)
2066
2120
  throw new EmmettError("Connection is required in context or options");
2067
2121
  return connection.withTransaction(
@@ -2087,7 +2141,7 @@ var sqliteWorkflowProcessor = (options) => {
2087
2141
  } = options;
2088
2142
  const hooks = {
2089
2143
  ..._nullishCoalesce(options.hooks, () => ( {})),
2090
- onClose: _optionalChain([options, 'access', _93 => _93.hooks, 'optionalAccess', _94 => _94.onClose])
2144
+ onClose: _optionalChain([options, 'access', _95 => _95.hooks, 'optionalAccess', _96 => _96.onClose])
2091
2145
  };
2092
2146
  return workflowProcessor({
2093
2147
  ...options,
@@ -2132,7 +2186,7 @@ var sqliteProjector = (options) => {
2132
2186
  } = options;
2133
2187
  const hooks = {
2134
2188
  ..._nullishCoalesce(options.hooks, () => ( {})),
2135
- onInit: options.projection.init !== void 0 || _optionalChain([options, 'access', _95 => _95.hooks, 'optionalAccess', _96 => _96.onInit]) ? async (context) => {
2189
+ onInit: options.projection.init !== void 0 || _optionalChain([options, 'access', _97 => _97.hooks, 'optionalAccess', _98 => _98.onInit]) ? async (context) => {
2136
2190
  if (options.projection.init)
2137
2191
  await options.projection.init({
2138
2192
  version: _nullishCoalesce(options.projection.version, () => ( version)),
@@ -2143,13 +2197,13 @@ var sqliteProjector = (options) => {
2143
2197
  migrationOptions: options.migrationOptions
2144
2198
  }
2145
2199
  });
2146
- if (_optionalChain([options, 'access', _97 => _97.hooks, 'optionalAccess', _98 => _98.onInit]))
2200
+ if (_optionalChain([options, 'access', _99 => _99.hooks, 'optionalAccess', _100 => _100.onInit]))
2147
2201
  await options.hooks.onInit({
2148
2202
  ...context,
2149
2203
  migrationOptions: options.migrationOptions
2150
2204
  });
2151
- } : _optionalChain([options, 'access', _99 => _99.hooks, 'optionalAccess', _100 => _100.onInit]),
2152
- onClose: _optionalChain([options, 'access', _101 => _101.hooks, 'optionalAccess', _102 => _102.onClose])
2205
+ } : _optionalChain([options, 'access', _101 => _101.hooks, 'optionalAccess', _102 => _102.onInit]),
2206
+ onClose: _optionalChain([options, 'access', _103 => _103.hooks, 'optionalAccess', _104 => _104.onClose])
2153
2207
  };
2154
2208
  const processor = projector({
2155
2209
  ...options,
@@ -2197,7 +2251,7 @@ var sqliteEventStoreConsumer = (options) => {
2197
2251
  })
2198
2252
  );
2199
2253
  return result.some(
2200
- (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _103 => _103.value, 'optionalAccess', _104 => _104.type]) !== "STOP"
2254
+ (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _105 => _105.value, 'optionalAccess', _106 => _106.type]) !== "STOP"
2201
2255
  ) ? void 0 : {
2202
2256
  type: "STOP"
2203
2257
  };
@@ -2211,7 +2265,7 @@ var sqliteEventStoreConsumer = (options) => {
2211
2265
  if (!isRunning) return;
2212
2266
  isRunning = false;
2213
2267
  if (messagePuller) {
2214
- _optionalChain([abortController, 'optionalAccess', _105 => _105.abort, 'call', _106 => _106()]);
2268
+ _optionalChain([abortController, 'optionalAccess', _107 => _107.abort, 'call', _108 => _108()]);
2215
2269
  await messagePuller.stop();
2216
2270
  }
2217
2271
  await start;
@@ -2286,8 +2340,8 @@ var sqliteEventStoreConsumer = (options) => {
2286
2340
  stopWhen: options.stopWhen,
2287
2341
  executor: pool.execute,
2288
2342
  eachBatch,
2289
- batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _107 => _107.batchSize]), () => ( DefaultSQLiteEventStoreProcessorBatchSize)),
2290
- pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _108 => _108.pullingFrequencyInMs]), () => ( DefaultSQLiteEventStoreProcessorPullingFrequencyInMs)),
2343
+ batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _109 => _109.batchSize]), () => ( DefaultSQLiteEventStoreProcessorBatchSize)),
2344
+ pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _110 => _110.pullingFrequencyInMs]), () => ( DefaultSQLiteEventStoreProcessorPullingFrequencyInMs)),
2291
2345
  signal: abortController.signal
2292
2346
  });
2293
2347
  start = (async () => {
@@ -2337,9 +2391,9 @@ var getSQLiteEventStore = (options) => {
2337
2391
  })));
2338
2392
  let migrateSchema = void 0;
2339
2393
  const inlineProjections = (_nullishCoalesce(options.projections, () => ( []))).filter(({ type }) => type === "inline").map(({ projection: projection2 }) => projection2);
2340
- const onBeforeCommitHook = _optionalChain([options, 'access', _109 => _109.hooks, 'optionalAccess', _110 => _110.onBeforeCommit]);
2394
+ const onBeforeCommitHook = _optionalChain([options, 'access', _111 => _111.hooks, 'optionalAccess', _112 => _112.onBeforeCommit]);
2341
2395
  if (options) {
2342
- autoGenerateSchema = _optionalChain([options, 'access', _111 => _111.schema, 'optionalAccess', _112 => _112.autoMigration]) === void 0 || _optionalChain([options, 'access', _113 => _113.schema, 'optionalAccess', _114 => _114.autoMigration]) !== "None";
2396
+ autoGenerateSchema = _optionalChain([options, 'access', _113 => _113.schema, 'optionalAccess', _114 => _114.autoMigration]) === void 0 || _optionalChain([options, 'access', _115 => _115.schema, 'optionalAccess', _116 => _116.autoMigration]) !== "None";
2343
2397
  }
2344
2398
  const migrate = (connection) => {
2345
2399
  if (!migrateSchema) {
@@ -2359,11 +2413,11 @@ var getSQLiteEventStore = (options) => {
2359
2413
  });
2360
2414
  }
2361
2415
  }
2362
- if (_optionalChain([options, 'access', _115 => _115.hooks, 'optionalAccess', _116 => _116.onBeforeSchemaCreated])) {
2416
+ if (_optionalChain([options, 'access', _117 => _117.hooks, 'optionalAccess', _118 => _118.onBeforeSchemaCreated])) {
2363
2417
  await options.hooks.onBeforeSchemaCreated(context);
2364
2418
  }
2365
2419
  },
2366
- onAfterSchemaCreated: _optionalChain([options, 'access', _117 => _117.hooks, 'optionalAccess', _118 => _118.onAfterSchemaCreated])
2420
+ onAfterSchemaCreated: _optionalChain([options, 'access', _119 => _119.hooks, 'optionalAccess', _120 => _120.onAfterSchemaCreated])
2367
2421
  });
2368
2422
  }
2369
2423
  return migrateSchema;
@@ -2376,7 +2430,7 @@ var getSQLiteEventStore = (options) => {
2376
2430
  async aggregateStream(streamName, options2) {
2377
2431
  await ensureSchemaExists();
2378
2432
  const { evolve, initialState, read } = options2;
2379
- const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _119 => _119.expectedStreamVersion]);
2433
+ const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _121 => _121.expectedStreamVersion]);
2380
2434
  let state = initialState();
2381
2435
  if (typeof streamName !== "string") {
2382
2436
  throw new Error("Stream name is not string");
@@ -2384,7 +2438,7 @@ var getSQLiteEventStore = (options) => {
2384
2438
  const result = await readStream(
2385
2439
  pool.execute,
2386
2440
  streamName,
2387
- { ...read, serializer: _nullishCoalesce(_optionalChain([read, 'optionalAccess', _120 => _120.serialization, 'optionalAccess', _121 => _121.serializer]), () => ( serializer)) }
2441
+ { ...read, serializer: _nullishCoalesce(_optionalChain([read, 'optionalAccess', _122 => _122.serialization, 'optionalAccess', _123 => _123.serializer]), () => ( serializer)) }
2388
2442
  );
2389
2443
  const currentStreamVersion = result.currentStreamVersion;
2390
2444
  assertExpectedVersionMatchesCurrent(
@@ -2406,7 +2460,7 @@ var getSQLiteEventStore = (options) => {
2406
2460
  await ensureSchemaExists();
2407
2461
  return readStream(pool.execute, streamName, {
2408
2462
  ...readOptions,
2409
- serializer: _nullishCoalesce(_optionalChain([options, 'access', _122 => _122.serialization, 'optionalAccess', _123 => _123.serializer]), () => ( serializer))
2463
+ serializer: _nullishCoalesce(_optionalChain([options, 'access', _124 => _124.serialization, 'optionalAccess', _125 => _125.serializer]), () => ( serializer))
2410
2464
  });
2411
2465
  },
2412
2466
  appendToStream: async (streamName, events, appendOptions) => {
@@ -2435,7 +2489,7 @@ var getSQLiteEventStore = (options) => {
2435
2489
  throw new ExpectedVersionConflictError(
2436
2490
  -1n,
2437
2491
  //TODO: Return actual version in case of error
2438
- _nullishCoalesce(_optionalChain([appendOptions, 'optionalAccess', _124 => _124.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
2492
+ _nullishCoalesce(_optionalChain([appendOptions, 'optionalAccess', _126 => _126.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
2439
2493
  );
2440
2494
  return {
2441
2495
  nextExpectedStreamVersion: appendResult.nextStreamPosition,
@@ -2493,13 +2547,13 @@ var readStream = async (execute, streamId, options) => {
2493
2547
  const { serializer } = options;
2494
2548
  const fromCondition = options.from ? _dumbo.SQL`AND stream_position >= ${options.from}` : _dumbo.SQL.EMPTY;
2495
2549
  const to = Number(
2496
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _125 => _125.to]), () => ( (_optionalChain([options, 'optionalAccess', _126 => _126.maxCount]) ? (_nullishCoalesce(options.from, () => ( 0n))) + options.maxCount : NaN)))
2550
+ _nullishCoalesce(_optionalChain([options, 'optionalAccess', _127 => _127.to]), () => ( (_optionalChain([options, 'optionalAccess', _128 => _128.maxCount]) ? (_nullishCoalesce(options.from, () => ( 0n))) + options.maxCount : NaN)))
2497
2551
  );
2498
2552
  const toCondition = !isNaN(to) ? _dumbo.SQL`AND stream_position <= ${to}` : _dumbo.SQL.EMPTY;
2499
2553
  const { rows: results } = await execute.query(
2500
2554
  _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
2501
2555
  FROM ${identifier6(messagesTable.name)}
2502
- WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _127 => _127.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
2556
+ WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _129 => _129.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
2503
2557
  ORDER BY stream_position ASC`
2504
2558
  );
2505
2559
  const messages = results.map((row) => {
@@ -2521,7 +2575,7 @@ var readStream = async (execute, streamId, options) => {
2521
2575
  kind: "Event",
2522
2576
  metadata
2523
2577
  };
2524
- return upcastRecordedMessage(event, _optionalChain([options, 'optionalAccess', _128 => _128.schema, 'optionalAccess', _129 => _129.versioning]));
2578
+ return upcastRecordedMessage(event, _optionalChain([options, 'optionalAccess', _130 => _130.schema, 'optionalAccess', _131 => _131.versioning]));
2525
2579
  });
2526
2580
  return messages.length > 0 ? {
2527
2581
  currentStreamVersion: messages[messages.length - 1].metadata.streamPosition,
@@ -2566,7 +2620,7 @@ async function storeSubscriptionCheckpointSQLite(execute, processorId, version,
2566
2620
  WHERE processor_id = ${processorId} AND partition = ${partition}`
2567
2621
  )
2568
2622
  );
2569
- const currentPosition = current_position && _optionalChain([current_position, 'optionalAccess', _130 => _130.last_processed_checkpoint]) !== null ? current_position.last_processed_checkpoint : null;
2623
+ const currentPosition = current_position && _optionalChain([current_position, 'optionalAccess', _132 => _132.last_processed_checkpoint]) !== null ? current_position.last_processed_checkpoint : null;
2570
2624
  if (currentPosition === position) {
2571
2625
  return 0;
2572
2626
  } else if (position !== null && currentPosition !== null && currentPosition > position) {
@@ -2594,7 +2648,7 @@ async function storeSubscriptionCheckpointSQLite(execute, processorId, version,
2594
2648
  WHERE processor_id = ${processorId} AND partition = ${partition}`
2595
2649
  )
2596
2650
  );
2597
- const currentPosition = current && _optionalChain([current, 'optionalAccess', _131 => _131.last_processed_checkpoint]) !== null ? BigInt(current.last_processed_checkpoint) : null;
2651
+ const currentPosition = current && _optionalChain([current, 'optionalAccess', _133 => _133.last_processed_checkpoint]) !== null ? BigInt(current.last_processed_checkpoint) : null;
2598
2652
  if (currentPosition === position) {
2599
2653
  return 0;
2600
2654
  } else {
@@ -2627,7 +2681,7 @@ var streamExists = (execute, streamId, options) => _dumbo.exists.call(void 0,
2627
2681
  _dumbo.SQL`SELECT EXISTS (
2628
2682
  SELECT 1
2629
2683
  from ${_dumbo.SQL.identifier(streamsTable.name)}
2630
- WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _132 => _132.partition]), () => ( defaultTag2))} AND is_archived = FALSE) as exists
2684
+ WHERE stream_id = ${streamId} AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _134 => _134.partition]), () => ( defaultTag2))} AND is_archived = FALSE) as exists
2631
2685
  `
2632
2686
  )
2633
2687
  );
@@ -2693,13 +2747,13 @@ var schemaSQL = [
2693
2747
  var createEventStoreSchema = async (pool, hooks) => {
2694
2748
  await pool.withTransaction(async (tx) => {
2695
2749
  await migration_0_42_0_FromSubscriptionsToProcessors(tx.execute);
2696
- if (_optionalChain([hooks, 'optionalAccess', _133 => _133.onBeforeSchemaCreated])) {
2750
+ if (_optionalChain([hooks, 'optionalAccess', _135 => _135.onBeforeSchemaCreated])) {
2697
2751
  await hooks.onBeforeSchemaCreated({
2698
2752
  connection: tx.connection
2699
2753
  });
2700
2754
  }
2701
2755
  await tx.execute.batchCommand(schemaSQL);
2702
- if (_optionalChain([hooks, 'optionalAccess', _134 => _134.onAfterSchemaCreated])) {
2756
+ if (_optionalChain([hooks, 'optionalAccess', _136 => _136.onAfterSchemaCreated])) {
2703
2757
  await hooks.onAfterSchemaCreated();
2704
2758
  }
2705
2759
  });