@event-driven-io/emmett-sqlite 0.43.0-beta.12 → 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;
629
+ if (storeCheckpointResult.success) {
630
+ lastCheckpoint = storeCheckpointResult.newCheckpoint;
712
631
  }
713
- if (stopAfter && stopAfter(upcasted)) {
714
- isActive = false;
715
- result = { type: "STOP", reason: "Stop condition reached" };
716
- break;
717
- }
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,7 +1068,7 @@ 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) {
1071
+ if (_optionalChain([options, 'access', _54 => _54.outputHandler, 'optionalAccess', _55 => _55.canHandle, 'access', _56 => _56.includes, 'call', _57 => _57(messageType)]) === true) {
1156
1072
  const recordedMessage = message2;
1157
1073
  const handledOutputMessages = options.outputHandler.eachBatch ? await options.outputHandler.eachBatch([recordedMessage], context) : await options.outputHandler.eachMessage(recordedMessage, context);
1158
1074
  if (handledOutputMessages instanceof EmmettError) {
@@ -1185,6 +1101,146 @@ var workflowProcessor = (options) => {
1185
1101
  });
1186
1102
  };
1187
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
+
1188
1244
  // src/eventStore/projections/pongo/pongoProjectionSpec.ts
1189
1245
 
1190
1246
 
@@ -1408,7 +1464,7 @@ var SQLiteProjectionSpec = {
1408
1464
  const allEvents = [];
1409
1465
  const run = async (connection) => {
1410
1466
  let globalPosition = 0n;
1411
- const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _56 => _56.numberOfTimes]), () => ( 1));
1467
+ const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _58 => _58.numberOfTimes]), () => ( 1));
1412
1468
  for (const event of [
1413
1469
  ...givenEvents,
1414
1470
  ...Array.from({ length: numberOfTimes }).flatMap(() => events)
@@ -1475,18 +1531,18 @@ var SQLiteProjectionSpec = {
1475
1531
  if (!isErrorConstructor(args[0])) {
1476
1532
  assertTrue(
1477
1533
  args[0](error),
1478
- `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()])}`
1479
1535
  );
1480
1536
  return;
1481
1537
  }
1482
1538
  assertTrue(
1483
1539
  error instanceof args[0],
1484
- `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()])}`
1485
1541
  );
1486
1542
  if (args[1]) {
1487
1543
  assertTrue(
1488
1544
  args[1](error),
1489
- `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()])}`
1490
1546
  );
1491
1547
  }
1492
1548
  }
@@ -1503,7 +1559,7 @@ var eventInStream = (streamName, event) => {
1503
1559
  ...event,
1504
1560
  metadata: {
1505
1561
  ..._nullishCoalesce(event.metadata, () => ( {})),
1506
- 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))
1507
1563
  }
1508
1564
  };
1509
1565
  };
@@ -1575,7 +1631,7 @@ var { identifier, merge } = _dumbo.SQL;
1575
1631
  var appendToStream = async (connection, streamName, streamType, messages, options) => {
1576
1632
  if (messages.length === 0) return { success: false };
1577
1633
  const expectedStreamVersion = toExpectedVersion(
1578
- _optionalChain([options, 'optionalAccess', _65 => _65.expectedStreamVersion])
1634
+ _optionalChain([options, 'optionalAccess', _67 => _67.expectedStreamVersion])
1579
1635
  );
1580
1636
  const messagesToAppend = messages.map(
1581
1637
  (m, i) => ({
@@ -1598,13 +1654,13 @@ var appendToStream = async (connection, streamName, streamType, messages, option
1598
1654
  streamType,
1599
1655
  downcastRecordedMessages(
1600
1656
  messagesToAppend,
1601
- _optionalChain([options, 'optionalAccess', _66 => _66.schema, 'optionalAccess', _67 => _67.versioning])
1657
+ _optionalChain([options, 'optionalAccess', _68 => _68.schema, 'optionalAccess', _69 => _69.versioning])
1602
1658
  ),
1603
1659
  {
1604
1660
  expectedStreamVersion
1605
1661
  }
1606
1662
  );
1607
- if (_optionalChain([options, 'optionalAccess', _68 => _68.onBeforeCommit]))
1663
+ if (_optionalChain([options, 'optionalAccess', _70 => _70.onBeforeCommit]))
1608
1664
  await options.onBeforeCommit(messagesToAppend, { connection });
1609
1665
  return { success: true, result };
1610
1666
  }
@@ -1628,7 +1684,7 @@ var toExpectedVersion = (expected) => {
1628
1684
  return expected;
1629
1685
  };
1630
1686
  var appendToStreamRaw = async (execute, streamId, streamType, messages, options) => {
1631
- let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _69 => _69.expectedStreamVersion]), () => ( null));
1687
+ let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _71 => _71.expectedStreamVersion]), () => ( null));
1632
1688
  const currentStreamVersion = await getLastStreamPosition(
1633
1689
  execute,
1634
1690
  streamId,
@@ -1646,7 +1702,7 @@ var appendToStreamRaw = async (execute, streamId, streamType, messages, options)
1646
1702
  VALUES (
1647
1703
  ${streamId},
1648
1704
  ${messages.length},
1649
- ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _70 => _70.partition]), () => ( streamsTable.columns.partition))},
1705
+ ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _72 => _72.partition]), () => ( streamsTable.columns.partition))},
1650
1706
  ${streamType},
1651
1707
  '[]',
1652
1708
  false
@@ -1656,7 +1712,7 @@ var appendToStreamRaw = async (execute, streamId, streamType, messages, options)
1656
1712
  SET stream_position = stream_position + ${messages.length}
1657
1713
  WHERE stream_id = ${streamId}
1658
1714
  AND stream_position = ${expectedStreamVersion}
1659
- 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))}
1660
1716
  AND is_archived = false
1661
1717
  RETURNING stream_position;
1662
1718
  `;
@@ -1664,12 +1720,12 @@ var appendToStreamRaw = async (execute, streamId, streamType, messages, options)
1664
1720
  messages,
1665
1721
  expectedStreamVersion,
1666
1722
  streamId,
1667
- _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))
1668
1724
  );
1669
1725
  const results = await execute.batchCommand([streamSQL, insertSQL], { assertChanges: true });
1670
1726
  const [streamResult, messagesResult] = results;
1671
- const streamPosition = _optionalChain([streamResult, 'optionalAccess', _75 => _75.rows, 'access', _76 => _76[0], 'optionalAccess', _77 => _77.stream_position]);
1672
- 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]);
1673
1729
  if (!streamPosition)
1674
1730
  throw new ExpectedVersionConflictError(0n, _nullishCoalesce(expectedStreamVersion, () => ( 0n)));
1675
1731
  if (!globalPosition) throw new Error("Could not find global position");
@@ -1685,7 +1741,7 @@ async function getLastStreamPosition(execute, streamId, expectedStreamVersion) {
1685
1741
  _dumbo.SQL`SELECT CAST(stream_position AS VARCHAR) AS stream_position FROM ${identifier(streamsTable.name)} WHERE stream_id = ${streamId}`
1686
1742
  )
1687
1743
  );
1688
- if (_optionalChain([result, 'optionalAccess', _82 => _82.stream_position]) == null) {
1744
+ if (_optionalChain([result, 'optionalAccess', _84 => _84.stream_position]) == null) {
1689
1745
  expectedStreamVersion = 0n;
1690
1746
  } else {
1691
1747
  expectedStreamVersion = BigInt(result.stream_position);
@@ -1694,7 +1750,7 @@ async function getLastStreamPosition(execute, streamId, expectedStreamVersion) {
1694
1750
  }
1695
1751
  var buildMessageInsertQuery = (messages, expectedStreamVersion, streamId, partition) => {
1696
1752
  const values = messages.map((message) => {
1697
- 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") {
1698
1754
  throw new Error("Stream position is required");
1699
1755
  }
1700
1756
  const streamPosition = BigInt(message.metadata.streamPosition) + BigInt(expectedStreamVersion);
@@ -1861,7 +1917,7 @@ var readLastMessageGlobalPosition = async (execute, options) => {
1861
1917
  _dumbo.SQL`
1862
1918
  SELECT global_position
1863
1919
  FROM ${identifier3(messagesTable.name)}
1864
- 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
1865
1921
  ORDER BY global_position
1866
1922
  LIMIT 1`
1867
1923
  )
@@ -1886,7 +1942,7 @@ var readMessagesBatch = async (execute, options) => {
1886
1942
  execute.query(
1887
1943
  _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
1888
1944
  FROM ${identifier4(messagesTable.name)}
1889
- 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}
1890
1946
  ORDER BY global_position
1891
1947
  ${limitCondition}`
1892
1948
  ),
@@ -1930,7 +1986,7 @@ var readProcessorCheckpoint = async (execute, options) => {
1930
1986
  execute.query(
1931
1987
  _dumbo.SQL`SELECT last_processed_checkpoint
1932
1988
  FROM ${identifier5(processorsTable.name)}
1933
- 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}
1934
1990
  LIMIT 1`
1935
1991
  )
1936
1992
  );
@@ -1968,7 +2024,7 @@ var sqliteEventStoreMessageBatchPuller = ({
1968
2024
  serializer
1969
2025
  };
1970
2026
  let waitTime = 100;
1971
- while (isRunning && !_optionalChain([signal, 'optionalAccess', _88 => _88.aborted])) {
2027
+ while (isRunning && !_optionalChain([signal, 'optionalAccess', _90 => _90.aborted])) {
1972
2028
  const { messages, currentGlobalPosition, areMessagesLeft } = await readMessagesBatch(executor, readMessagesOptions);
1973
2029
  if (messages.length > 0) {
1974
2030
  const result = await eachBatch(messages);
@@ -1979,7 +2035,7 @@ var sqliteEventStoreMessageBatchPuller = ({
1979
2035
  }
1980
2036
  readMessagesOptions.after = currentGlobalPosition;
1981
2037
  await new Promise((resolve) => setTimeout(resolve, waitTime));
1982
- if (_optionalChain([stopWhen, 'optionalAccess', _89 => _89.noMessagesLeft]) === true && !areMessagesLeft) {
2038
+ if (_optionalChain([stopWhen, 'optionalAccess', _91 => _91.noMessagesLeft]) === true && !areMessagesLeft) {
1983
2039
  isRunning = false;
1984
2040
  break;
1985
2041
  }
@@ -2024,7 +2080,7 @@ var zipSQLiteEventStoreMessageBatchPullerStartFrom = (options) => {
2024
2080
  var sqliteCheckpointer = () => ({
2025
2081
  read: async (options, context) => {
2026
2082
  const result = await readProcessorCheckpoint(context.execute, options);
2027
- return { lastCheckpoint: _optionalChain([result, 'optionalAccess', _90 => _90.lastProcessedCheckpoint]) };
2083
+ return { lastCheckpoint: _optionalChain([result, 'optionalAccess', _92 => _92.lastProcessedCheckpoint]) };
2028
2084
  },
2029
2085
  store: async (options, context) => {
2030
2086
  const newCheckpoint = getCheckpoint(options.message);
@@ -2042,7 +2098,7 @@ var sqliteCheckpointer = () => ({
2042
2098
  // src/eventStore/consumers/sqliteProcessor.ts
2043
2099
  var sqliteProcessingScope = () => {
2044
2100
  const processingScope = async (handler, partialContext) => {
2045
- const connection = _optionalChain([partialContext, 'optionalAccess', _91 => _91.connection]);
2101
+ const connection = _optionalChain([partialContext, 'optionalAccess', _93 => _93.connection]);
2046
2102
  if (!connection)
2047
2103
  throw new EmmettError("Connection is required in context or options");
2048
2104
  return connection.withTransaction(
@@ -2059,7 +2115,7 @@ var sqliteProcessingScope = () => {
2059
2115
  };
2060
2116
  var sqliteWorkflowProcessingScope = (messageStore) => {
2061
2117
  const processingScope = async (handler, partialContext) => {
2062
- const connection = _optionalChain([partialContext, 'optionalAccess', _92 => _92.connection]);
2118
+ const connection = _optionalChain([partialContext, 'optionalAccess', _94 => _94.connection]);
2063
2119
  if (!connection)
2064
2120
  throw new EmmettError("Connection is required in context or options");
2065
2121
  return connection.withTransaction(
@@ -2085,7 +2141,7 @@ var sqliteWorkflowProcessor = (options) => {
2085
2141
  } = options;
2086
2142
  const hooks = {
2087
2143
  ..._nullishCoalesce(options.hooks, () => ( {})),
2088
- onClose: _optionalChain([options, 'access', _93 => _93.hooks, 'optionalAccess', _94 => _94.onClose])
2144
+ onClose: _optionalChain([options, 'access', _95 => _95.hooks, 'optionalAccess', _96 => _96.onClose])
2089
2145
  };
2090
2146
  return workflowProcessor({
2091
2147
  ...options,
@@ -2130,7 +2186,7 @@ var sqliteProjector = (options) => {
2130
2186
  } = options;
2131
2187
  const hooks = {
2132
2188
  ..._nullishCoalesce(options.hooks, () => ( {})),
2133
- 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) => {
2134
2190
  if (options.projection.init)
2135
2191
  await options.projection.init({
2136
2192
  version: _nullishCoalesce(options.projection.version, () => ( version)),
@@ -2141,13 +2197,13 @@ var sqliteProjector = (options) => {
2141
2197
  migrationOptions: options.migrationOptions
2142
2198
  }
2143
2199
  });
2144
- if (_optionalChain([options, 'access', _97 => _97.hooks, 'optionalAccess', _98 => _98.onInit]))
2200
+ if (_optionalChain([options, 'access', _99 => _99.hooks, 'optionalAccess', _100 => _100.onInit]))
2145
2201
  await options.hooks.onInit({
2146
2202
  ...context,
2147
2203
  migrationOptions: options.migrationOptions
2148
2204
  });
2149
- } : _optionalChain([options, 'access', _99 => _99.hooks, 'optionalAccess', _100 => _100.onInit]),
2150
- 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])
2151
2207
  };
2152
2208
  const processor = projector({
2153
2209
  ...options,
@@ -2195,7 +2251,7 @@ var sqliteEventStoreConsumer = (options) => {
2195
2251
  })
2196
2252
  );
2197
2253
  return result.some(
2198
- (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"
2199
2255
  ) ? void 0 : {
2200
2256
  type: "STOP"
2201
2257
  };
@@ -2209,7 +2265,7 @@ var sqliteEventStoreConsumer = (options) => {
2209
2265
  if (!isRunning) return;
2210
2266
  isRunning = false;
2211
2267
  if (messagePuller) {
2212
- _optionalChain([abortController, 'optionalAccess', _105 => _105.abort, 'call', _106 => _106()]);
2268
+ _optionalChain([abortController, 'optionalAccess', _107 => _107.abort, 'call', _108 => _108()]);
2213
2269
  await messagePuller.stop();
2214
2270
  }
2215
2271
  await start;
@@ -2284,8 +2340,8 @@ var sqliteEventStoreConsumer = (options) => {
2284
2340
  stopWhen: options.stopWhen,
2285
2341
  executor: pool.execute,
2286
2342
  eachBatch,
2287
- batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _107 => _107.batchSize]), () => ( DefaultSQLiteEventStoreProcessorBatchSize)),
2288
- 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)),
2289
2345
  signal: abortController.signal
2290
2346
  });
2291
2347
  start = (async () => {
@@ -2335,9 +2391,9 @@ var getSQLiteEventStore = (options) => {
2335
2391
  })));
2336
2392
  let migrateSchema = void 0;
2337
2393
  const inlineProjections = (_nullishCoalesce(options.projections, () => ( []))).filter(({ type }) => type === "inline").map(({ projection: projection2 }) => projection2);
2338
- 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]);
2339
2395
  if (options) {
2340
- 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";
2341
2397
  }
2342
2398
  const migrate = (connection) => {
2343
2399
  if (!migrateSchema) {
@@ -2357,11 +2413,11 @@ var getSQLiteEventStore = (options) => {
2357
2413
  });
2358
2414
  }
2359
2415
  }
2360
- if (_optionalChain([options, 'access', _115 => _115.hooks, 'optionalAccess', _116 => _116.onBeforeSchemaCreated])) {
2416
+ if (_optionalChain([options, 'access', _117 => _117.hooks, 'optionalAccess', _118 => _118.onBeforeSchemaCreated])) {
2361
2417
  await options.hooks.onBeforeSchemaCreated(context);
2362
2418
  }
2363
2419
  },
2364
- onAfterSchemaCreated: _optionalChain([options, 'access', _117 => _117.hooks, 'optionalAccess', _118 => _118.onAfterSchemaCreated])
2420
+ onAfterSchemaCreated: _optionalChain([options, 'access', _119 => _119.hooks, 'optionalAccess', _120 => _120.onAfterSchemaCreated])
2365
2421
  });
2366
2422
  }
2367
2423
  return migrateSchema;
@@ -2374,7 +2430,7 @@ var getSQLiteEventStore = (options) => {
2374
2430
  async aggregateStream(streamName, options2) {
2375
2431
  await ensureSchemaExists();
2376
2432
  const { evolve, initialState, read } = options2;
2377
- const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _119 => _119.expectedStreamVersion]);
2433
+ const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _121 => _121.expectedStreamVersion]);
2378
2434
  let state = initialState();
2379
2435
  if (typeof streamName !== "string") {
2380
2436
  throw new Error("Stream name is not string");
@@ -2382,7 +2438,7 @@ var getSQLiteEventStore = (options) => {
2382
2438
  const result = await readStream(
2383
2439
  pool.execute,
2384
2440
  streamName,
2385
- { ...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)) }
2386
2442
  );
2387
2443
  const currentStreamVersion = result.currentStreamVersion;
2388
2444
  assertExpectedVersionMatchesCurrent(
@@ -2404,7 +2460,7 @@ var getSQLiteEventStore = (options) => {
2404
2460
  await ensureSchemaExists();
2405
2461
  return readStream(pool.execute, streamName, {
2406
2462
  ...readOptions,
2407
- 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))
2408
2464
  });
2409
2465
  },
2410
2466
  appendToStream: async (streamName, events, appendOptions) => {
@@ -2433,7 +2489,7 @@ var getSQLiteEventStore = (options) => {
2433
2489
  throw new ExpectedVersionConflictError(
2434
2490
  -1n,
2435
2491
  //TODO: Return actual version in case of error
2436
- _nullishCoalesce(_optionalChain([appendOptions, 'optionalAccess', _124 => _124.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
2492
+ _nullishCoalesce(_optionalChain([appendOptions, 'optionalAccess', _126 => _126.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
2437
2493
  );
2438
2494
  return {
2439
2495
  nextExpectedStreamVersion: appendResult.nextStreamPosition,
@@ -2491,13 +2547,13 @@ var readStream = async (execute, streamId, options) => {
2491
2547
  const { serializer } = options;
2492
2548
  const fromCondition = options.from ? _dumbo.SQL`AND stream_position >= ${options.from}` : _dumbo.SQL.EMPTY;
2493
2549
  const to = Number(
2494
- _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)))
2495
2551
  );
2496
2552
  const toCondition = !isNaN(to) ? _dumbo.SQL`AND stream_position <= ${to}` : _dumbo.SQL.EMPTY;
2497
2553
  const { rows: results } = await execute.query(
2498
2554
  _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
2499
2555
  FROM ${identifier6(messagesTable.name)}
2500
- 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}
2501
2557
  ORDER BY stream_position ASC`
2502
2558
  );
2503
2559
  const messages = results.map((row) => {
@@ -2519,7 +2575,7 @@ var readStream = async (execute, streamId, options) => {
2519
2575
  kind: "Event",
2520
2576
  metadata
2521
2577
  };
2522
- 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]));
2523
2579
  });
2524
2580
  return messages.length > 0 ? {
2525
2581
  currentStreamVersion: messages[messages.length - 1].metadata.streamPosition,
@@ -2564,7 +2620,7 @@ async function storeSubscriptionCheckpointSQLite(execute, processorId, version,
2564
2620
  WHERE processor_id = ${processorId} AND partition = ${partition}`
2565
2621
  )
2566
2622
  );
2567
- 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;
2568
2624
  if (currentPosition === position) {
2569
2625
  return 0;
2570
2626
  } else if (position !== null && currentPosition !== null && currentPosition > position) {
@@ -2592,7 +2648,7 @@ async function storeSubscriptionCheckpointSQLite(execute, processorId, version,
2592
2648
  WHERE processor_id = ${processorId} AND partition = ${partition}`
2593
2649
  )
2594
2650
  );
2595
- 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;
2596
2652
  if (currentPosition === position) {
2597
2653
  return 0;
2598
2654
  } else {
@@ -2625,7 +2681,7 @@ var streamExists = (execute, streamId, options) => _dumbo.exists.call(void 0,
2625
2681
  _dumbo.SQL`SELECT EXISTS (
2626
2682
  SELECT 1
2627
2683
  from ${_dumbo.SQL.identifier(streamsTable.name)}
2628
- 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
2629
2685
  `
2630
2686
  )
2631
2687
  );
@@ -2691,13 +2747,13 @@ var schemaSQL = [
2691
2747
  var createEventStoreSchema = async (pool, hooks) => {
2692
2748
  await pool.withTransaction(async (tx) => {
2693
2749
  await migration_0_42_0_FromSubscriptionsToProcessors(tx.execute);
2694
- if (_optionalChain([hooks, 'optionalAccess', _133 => _133.onBeforeSchemaCreated])) {
2750
+ if (_optionalChain([hooks, 'optionalAccess', _135 => _135.onBeforeSchemaCreated])) {
2695
2751
  await hooks.onBeforeSchemaCreated({
2696
2752
  connection: tx.connection
2697
2753
  });
2698
2754
  }
2699
2755
  await tx.execute.batchCommand(schemaSQL);
2700
- if (_optionalChain([hooks, 'optionalAccess', _134 => _134.onAfterSchemaCreated])) {
2756
+ if (_optionalChain([hooks, 'optionalAccess', _136 => _136.onAfterSchemaCreated])) {
2701
2757
  await hooks.onAfterSchemaCreated();
2702
2758
  }
2703
2759
  });