@event-driven-io/emmett-sqlite 0.43.0-beta.12 → 0.43.0-beta.14

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,1707 +1,471 @@
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
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let _event_driven_io_emmett = require("@event-driven-io/emmett");
3
+ let _event_driven_io_pongo = require("@event-driven-io/pongo");
4
+ let _event_driven_io_dumbo = require("@event-driven-io/dumbo");
5
+ let uuid = require("uuid");
6
+
7
+ //#region src/eventStore/projections/pongo/pongoProjections.ts
8
+ const pongoProjection = ({ name, kind, version, truncate, handle, canHandle, eventsOptions }) => sqliteProjection({
9
+ name,
10
+ version,
11
+ kind: kind ?? "emt:projections:postgresql:pongo:generic",
12
+ canHandle,
13
+ eventsOptions,
14
+ handle: async (events, context) => {
15
+ const { connection } = context;
16
+ const pongo = (0, _event_driven_io_pongo.pongoClient)({
17
+ driver: await pongoDriverRegistry.tryResolve(context.driverType),
18
+ connectionOptions: { connection }
19
+ });
20
+ try {
21
+ await handle(events, {
22
+ ...context,
23
+ pongo
24
+ });
25
+ } finally {
26
+ await pongo.close();
27
+ }
28
+ },
29
+ truncate: truncate ? async (context) => {
30
+ const { connection } = context;
31
+ const pongo = (0, _event_driven_io_pongo.pongoClient)({
32
+ driver: await pongoDriverRegistry.tryResolve(context.driverType),
33
+ connectionOptions: { connection }
34
+ });
35
+ try {
36
+ await truncate({
37
+ ...context,
38
+ pongo
39
+ });
40
+ } finally {
41
+ await pongo.close();
42
+ }
43
+ } : void 0
55
44
  });
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
129
- var isNumber = (val) => typeof val === "number" && val === val;
130
- var isString = (val) => typeof val === "string";
131
- var isErrorConstructor = (expect) => {
132
- return typeof expect === "function" && expect.prototype && // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
133
- expect.prototype.constructor === expect;
134
- };
135
- var EmmettError = (_class = class _EmmettError extends Error {
136
- static __initStatic() {this.Codes = {
137
- ValidationError: 400,
138
- IllegalStateError: 403,
139
- NotFoundError: 404,
140
- ConcurrencyError: 412,
141
- InternalServerError: 500
142
- }}
143
-
144
- constructor(options) {
145
- const errorCode = options && typeof options === "object" && "errorCode" in options ? options.errorCode : isNumber(options) ? options : _EmmettError.Codes.InternalServerError;
146
- const message = options && typeof options === "object" && "message" in options ? options.message : isString(options) ? options : `Error with status code '${errorCode}' ocurred during Emmett processing`;
147
- super(message);
148
- this.errorCode = errorCode;
149
- Object.setPrototypeOf(this, _EmmettError.prototype);
150
- }
151
- static mapFrom(error) {
152
- if (_EmmettError.isInstanceOf(error)) {
153
- return error;
154
- }
155
- return new _EmmettError({
156
- errorCode: "errorCode" in error && error.errorCode !== void 0 && error.errorCode !== null ? error.errorCode : _EmmettError.Codes.InternalServerError,
157
- message: _nullishCoalesce(error.message, () => ( "An unknown error occurred"))
158
- });
159
- }
160
- static isInstanceOf(error, errorCode) {
161
- return typeof error === "object" && error !== null && "errorCode" in error && isNumber(error.errorCode) && (errorCode === void 0 || error.errorCode === errorCode);
162
- }
163
- }, _class.__initStatic(), _class);
164
- var ConcurrencyError = class _ConcurrencyError extends EmmettError {
165
- constructor(current, expected, message) {
166
- super({
167
- errorCode: EmmettError.Codes.ConcurrencyError,
168
- message: _nullishCoalesce(message, () => ( `Expected version ${expected.toString()} does not match current ${_optionalChain([current, 'optionalAccess', _ => _.toString, 'call', _2 => _2()])}`))
169
- });
170
- this.current = current;
171
- this.expected = expected;
172
- Object.setPrototypeOf(this, _ConcurrencyError.prototype);
173
- }
174
- };
175
-
176
- // ../emmett/dist/index.js
177
- var _uuid = require('uuid');
178
-
179
-
180
- var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefault(_asyncretry);
181
-
182
-
183
-
184
- var emmettPrefix = "emt";
185
- var defaultTag = `${emmettPrefix}:default`;
186
- var unknownTag = `${emmettPrefix}:unknown`;
187
- var canCreateEventStoreSession = (eventStore) => "withSession" in eventStore;
188
- var nulloSessionFactory = (eventStore) => ({
189
- withSession: (callback) => {
190
- const nulloSession = {
191
- eventStore,
192
- close: () => Promise.resolve()
193
- };
194
- return callback(nulloSession);
195
- }
45
+ const pongoMultiStreamProjection = (options) => {
46
+ const { collectionName, getDocumentId, canHandle } = options;
47
+ const collectionNameWithVersion = options.version && options.version > 0 ? `${collectionName}_v${options.version}` : collectionName;
48
+ return pongoProjection({
49
+ name: collectionNameWithVersion,
50
+ version: options.version,
51
+ kind: options.kind ?? "emt:projections:postgresql:pongo:multi_stream",
52
+ eventsOptions: options.eventsOptions,
53
+ handle: async (events, { pongo }) => {
54
+ const collection = pongo.db().collection(collectionNameWithVersion, options.collectionOptions);
55
+ const eventsByDocumentId = events.map((event) => {
56
+ return {
57
+ documentId: getDocumentId(event),
58
+ event
59
+ };
60
+ }).reduce((acc, { documentId, event }) => {
61
+ if (!acc.has(documentId)) acc.set(documentId, []);
62
+ acc.get(documentId).push(event);
63
+ return acc;
64
+ }, /* @__PURE__ */ new Map());
65
+ await collection.handle([...eventsByDocumentId.keys()], (document, id) => {
66
+ return (0, _event_driven_io_emmett.reduceAsync)(eventsByDocumentId.get(id), async (acc, event) => await options.evolve(acc, event), document ?? ("initialState" in options ? options.initialState() : null));
67
+ });
68
+ },
69
+ canHandle,
70
+ truncate: async (context) => {
71
+ const { connection } = context;
72
+ const pongo = (0, _event_driven_io_pongo.pongoClient)({
73
+ driver: await pongoDriverRegistry.tryResolve(context.driverType),
74
+ connectionOptions: { connection }
75
+ });
76
+ try {
77
+ await pongo.db().collection(collectionNameWithVersion, options.collectionOptions).deleteMany();
78
+ } finally {
79
+ await pongo.close();
80
+ }
81
+ },
82
+ init: async (context) => {
83
+ const { connection } = context;
84
+ const driver = await pongoDriverRegistry.tryResolve(context.driverType);
85
+ const pongo = (0, _event_driven_io_pongo.pongoClient)({
86
+ connectionOptions: { connection },
87
+ driver
88
+ });
89
+ try {
90
+ await pongo.db().collection(collectionNameWithVersion, options.collectionOptions).schema.migrate();
91
+ } finally {
92
+ await pongo.close();
93
+ }
94
+ }
95
+ });
96
+ };
97
+ const pongoSingleStreamProjection = (options) => {
98
+ return pongoMultiStreamProjection({
99
+ ...options,
100
+ kind: "emt:projections:postgresql:pongo:single_stream",
101
+ getDocumentId: options.getDocumentId ?? ((event) => event.metadata.streamName)
102
+ });
103
+ };
104
+
105
+ //#endregion
106
+ //#region src/eventStore/projections/pongo/pongoProjectionSpec.ts
107
+ const withCollection = async (handle, options) => {
108
+ const { connection, inDatabase, inCollection } = options;
109
+ const driver = await pongoDriverRegistry.tryResolve(connection.driverType);
110
+ const pongo = (0, _event_driven_io_pongo.pongoClient)({
111
+ connectionOptions: { connection },
112
+ driver
113
+ });
114
+ try {
115
+ return handle(pongo.db(inDatabase).collection(inCollection));
116
+ } finally {
117
+ await pongo.close();
118
+ }
119
+ };
120
+ const withoutIdAndVersion = (doc) => {
121
+ const { _id, _version, ...without } = doc;
122
+ return without;
123
+ };
124
+ const assertDocumentsEqual = (actual, expected) => {
125
+ if ("_id" in expected) (0, _event_driven_io_emmett.assertEqual)(expected._id, actual._id, `Document ids are not matching! Expected: ${expected._id}, Actual: ${actual._id}`);
126
+ return (0, _event_driven_io_emmett.assertDeepEqual)(withoutIdAndVersion(actual), withoutIdAndVersion(expected));
127
+ };
128
+ const documentExists = (document, options) => (assertOptions) => withCollection(async (collection) => {
129
+ const result = await collection.findOne("withId" in options ? { _id: options.withId } : options.matchingFilter);
130
+ (0, _event_driven_io_emmett.assertIsNotNull)(result);
131
+ assertDocumentsEqual(result, document);
132
+ }, {
133
+ ...options,
134
+ ...assertOptions
196
135
  });
197
- var STREAM_EXISTS = "STREAM_EXISTS";
198
- var STREAM_DOES_NOT_EXIST = "STREAM_DOES_NOT_EXIST";
199
- var NO_CONCURRENCY_CHECK = "NO_CONCURRENCY_CHECK";
200
- var matchesExpectedVersion = (current, expected, defaultVersion) => {
201
- if (expected === NO_CONCURRENCY_CHECK) return true;
202
- if (expected == STREAM_DOES_NOT_EXIST) return current === defaultVersion;
203
- if (expected == STREAM_EXISTS) return current !== defaultVersion;
204
- return current === expected;
205
- };
206
- var assertExpectedVersionMatchesCurrent = (current, expected, defaultVersion) => {
207
- expected ??= NO_CONCURRENCY_CHECK;
208
- if (!matchesExpectedVersion(current, expected, defaultVersion))
209
- throw new ExpectedVersionConflictError(current, expected);
210
- };
211
- var ExpectedVersionConflictError = class _ExpectedVersionConflictError extends ConcurrencyError {
212
- constructor(current, expected) {
213
- super(_optionalChain([current, 'optionalAccess', _3 => _3.toString, 'call', _4 => _4()]), _optionalChain([expected, 'optionalAccess', _5 => _5.toString, 'call', _6 => _6()]));
214
- Object.setPrototypeOf(this, _ExpectedVersionConflictError.prototype);
215
- }
216
- };
217
- var isExpectedVersionConflictError = (error) => error instanceof ExpectedVersionConflictError || EmmettError.isInstanceOf(
218
- error,
219
- ExpectedVersionConflictError.Codes.ConcurrencyError
220
- );
221
- var isPrimitive = (value) => {
222
- const type = typeof value;
223
- return value === null || value === void 0 || type === "boolean" || type === "number" || type === "string" || type === "symbol" || type === "bigint";
224
- };
225
- var compareArrays = (left, right) => {
226
- if (left.length !== right.length) {
227
- return false;
228
- }
229
- for (let i = 0; i < left.length; i++) {
230
- const leftHas = i in left;
231
- const rightHas = i in right;
232
- if (leftHas !== rightHas) return false;
233
- if (leftHas && !deepEquals(left[i], right[i])) return false;
234
- }
235
- return true;
236
- };
237
- var compareDates = (left, right) => {
238
- return left.getTime() === right.getTime();
239
- };
240
- var compareRegExps = (left, right) => {
241
- return left.toString() === right.toString();
242
- };
243
- var compareErrors = (left, right) => {
244
- if (left.message !== right.message || left.name !== right.name) {
245
- return false;
246
- }
247
- const leftKeys = Object.keys(left);
248
- const rightKeys = Object.keys(right);
249
- if (leftKeys.length !== rightKeys.length) return false;
250
- const rightKeySet = new Set(rightKeys);
251
- for (const key of leftKeys) {
252
- if (!rightKeySet.has(key)) return false;
253
- if (!deepEquals(left[key], right[key])) return false;
254
- }
255
- return true;
256
- };
257
- var compareMaps = (left, right) => {
258
- if (left.size !== right.size) return false;
259
- for (const [key, value] of left) {
260
- if (isPrimitive(key)) {
261
- if (!right.has(key) || !deepEquals(value, right.get(key))) {
262
- return false;
263
- }
264
- } else {
265
- let found = false;
266
- for (const [rightKey, rightValue] of right) {
267
- if (deepEquals(key, rightKey) && deepEquals(value, rightValue)) {
268
- found = true;
269
- break;
270
- }
271
- }
272
- if (!found) return false;
273
- }
274
- }
275
- return true;
276
- };
277
- var compareSets = (left, right) => {
278
- if (left.size !== right.size) return false;
279
- for (const leftItem of left) {
280
- if (isPrimitive(leftItem)) {
281
- if (!right.has(leftItem)) return false;
282
- } else {
283
- let found = false;
284
- for (const rightItem of right) {
285
- if (deepEquals(leftItem, rightItem)) {
286
- found = true;
287
- break;
288
- }
289
- }
290
- if (!found) return false;
291
- }
292
- }
293
- return true;
294
- };
295
- var compareArrayBuffers = (left, right) => {
296
- if (left.byteLength !== right.byteLength) return false;
297
- const leftView = new Uint8Array(left);
298
- const rightView = new Uint8Array(right);
299
- for (let i = 0; i < leftView.length; i++) {
300
- if (leftView[i] !== rightView[i]) return false;
301
- }
302
- return true;
303
- };
304
- var compareTypedArrays = (left, right) => {
305
- if (left.constructor !== right.constructor) return false;
306
- if (left.byteLength !== right.byteLength) return false;
307
- const leftArray = new Uint8Array(
308
- left.buffer,
309
- left.byteOffset,
310
- left.byteLength
311
- );
312
- const rightArray = new Uint8Array(
313
- right.buffer,
314
- right.byteOffset,
315
- right.byteLength
316
- );
317
- for (let i = 0; i < leftArray.length; i++) {
318
- if (leftArray[i] !== rightArray[i]) return false;
319
- }
320
- return true;
321
- };
322
- var compareObjects = (left, right) => {
323
- const keys1 = Object.keys(left);
324
- const keys2 = Object.keys(right);
325
- if (keys1.length !== keys2.length) {
326
- return false;
327
- }
328
- for (const key of keys1) {
329
- if (left[key] instanceof Function && right[key] instanceof Function) {
330
- continue;
331
- }
332
- const isEqual = deepEquals(left[key], right[key]);
333
- if (!isEqual) {
334
- return false;
335
- }
336
- }
337
- return true;
338
- };
339
- var getType = (value) => {
340
- if (value === null) return "null";
341
- if (value === void 0) return "undefined";
342
- const primitiveType = typeof value;
343
- if (primitiveType !== "object") return primitiveType;
344
- if (Array.isArray(value)) return "array";
345
- if (value instanceof Boolean) return "boxed-boolean";
346
- if (value instanceof Number) return "boxed-number";
347
- if (value instanceof String) return "boxed-string";
348
- if (value instanceof Date) return "date";
349
- if (value instanceof RegExp) return "regexp";
350
- if (value instanceof Error) return "error";
351
- if (value instanceof Map) return "map";
352
- if (value instanceof Set) return "set";
353
- if (value instanceof ArrayBuffer) return "arraybuffer";
354
- if (value instanceof DataView) return "dataview";
355
- if (value instanceof WeakMap) return "weakmap";
356
- if (value instanceof WeakSet) return "weakset";
357
- if (ArrayBuffer.isView(value)) return "typedarray";
358
- return "object";
359
- };
360
- var deepEquals = (left, right) => {
361
- if (left === right) return true;
362
- if (isEquatable(left)) {
363
- return left.equals(right);
364
- }
365
- const leftType = getType(left);
366
- const rightType = getType(right);
367
- if (leftType !== rightType) return false;
368
- switch (leftType) {
369
- case "null":
370
- case "undefined":
371
- case "boolean":
372
- case "number":
373
- case "bigint":
374
- case "string":
375
- case "symbol":
376
- case "function":
377
- return left === right;
378
- case "array":
379
- return compareArrays(left, right);
380
- case "date":
381
- return compareDates(left, right);
382
- case "regexp":
383
- return compareRegExps(left, right);
384
- case "error":
385
- return compareErrors(left, right);
386
- case "map":
387
- return compareMaps(
388
- left,
389
- right
390
- );
391
- case "set":
392
- return compareSets(left, right);
393
- case "arraybuffer":
394
- return compareArrayBuffers(left, right);
395
- case "dataview":
396
- case "weakmap":
397
- case "weakset":
398
- return false;
399
- case "typedarray":
400
- return compareTypedArrays(
401
- left,
402
- right
403
- );
404
- case "boxed-boolean":
405
- return left.valueOf() === right.valueOf();
406
- case "boxed-number":
407
- return left.valueOf() === right.valueOf();
408
- case "boxed-string":
409
- return left.valueOf() === right.valueOf();
410
- case "object":
411
- return compareObjects(
412
- left,
413
- right
414
- );
415
- default:
416
- return false;
417
- }
418
- };
419
- var isEquatable = (left) => {
420
- return left !== null && left !== void 0 && typeof left === "object" && "equals" in left && typeof left["equals"] === "function";
421
- };
422
- var toNormalizedString = (value) => value.toString().padStart(19, "0");
423
- var bigInt = {
424
- toNormalizedString
425
- };
426
- var bigIntReplacer = (_key, value) => {
427
- return typeof value === "bigint" ? value.toString() : value;
428
- };
429
- var dateReplacer = (_key, value) => {
430
- return value instanceof Date ? value.toISOString() : value;
431
- };
432
- var isFirstLetterNumeric = (str) => {
433
- const c = str.charCodeAt(0);
434
- return c >= 48 && c <= 57;
435
- };
436
- var isFirstLetterNumericOrMinus = (str) => {
437
- const c = str.charCodeAt(0);
438
- return c >= 48 && c <= 57 || c === 45;
439
- };
440
- var bigIntReviver = (_key, value, context) => {
441
- if (typeof value === "number" && Number.isInteger(value) && !Number.isSafeInteger(value)) {
442
- try {
443
- return BigInt(_nullishCoalesce(_optionalChain([context, 'optionalAccess', _7 => _7.source]), () => ( value.toString())));
444
- } catch (e2) {
445
- return value;
446
- }
447
- }
448
- if (typeof value === "string" && value.length > 15) {
449
- if (isFirstLetterNumericOrMinus(value)) {
450
- const num = Number(value);
451
- if (Number.isFinite(num) && !Number.isSafeInteger(num)) {
452
- try {
453
- return BigInt(value);
454
- } catch (e3) {
455
- }
456
- }
457
- }
458
- }
459
- return value;
460
- };
461
- var dateReviver = (_key, value) => {
462
- if (typeof value === "string" && value.length === 24 && isFirstLetterNumeric(value) && value[10] === "T" && value[23] === "Z") {
463
- const date = new Date(value);
464
- if (!isNaN(date.getTime())) {
465
- return date;
466
- }
467
- }
468
- return value;
469
- };
470
- var composeJSONReplacers = (...replacers) => {
471
- const filteredReplacers = replacers.filter((r) => r !== void 0);
472
- if (filteredReplacers.length === 0) return void 0;
473
- return (key, value) => (
474
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
475
- filteredReplacers.reduce(
476
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
477
- (accValue, replacer) => replacer(key, accValue),
478
- value
479
- )
480
- );
481
- };
482
- var composeJSONRevivers = (...revivers) => {
483
- const filteredRevivers = revivers.filter((r) => r !== void 0);
484
- if (filteredRevivers.length === 0) return void 0;
485
- return (key, value, context) => (
486
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
487
- filteredRevivers.reduce(
488
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
489
- (accValue, reviver) => reviver(key, accValue, context),
490
- value
491
- )
492
- );
493
- };
494
- var JSONReplacer = (opts) => composeJSONReplacers(
495
- _optionalChain([opts, 'optionalAccess', _8 => _8.replacer]),
496
- _optionalChain([opts, 'optionalAccess', _9 => _9.failOnBigIntSerialization]) !== true ? JSONReplacers.bigInt : void 0,
497
- _optionalChain([opts, 'optionalAccess', _10 => _10.useDefaultDateSerialization]) !== true ? JSONReplacers.date : void 0
498
- );
499
- var JSONReviver = (opts) => composeJSONRevivers(
500
- _optionalChain([opts, 'optionalAccess', _11 => _11.reviver]),
501
- _optionalChain([opts, 'optionalAccess', _12 => _12.parseBigInts]) === true ? JSONRevivers.bigInt : void 0,
502
- _optionalChain([opts, 'optionalAccess', _13 => _13.parseDates]) === true ? JSONRevivers.date : void 0
503
- );
504
- var JSONReplacers = {
505
- bigInt: bigIntReplacer,
506
- date: dateReplacer
507
- };
508
- var JSONRevivers = {
509
- bigInt: bigIntReviver,
510
- date: dateReviver
511
- };
512
- var jsonSerializer = (options) => {
513
- const defaultReplacer = JSONReplacer(options);
514
- const defaultReviver = JSONReviver(options);
515
- return {
516
- serialize: (object, serializerOptions) => JSON.stringify(
517
- object,
518
- serializerOptions ? JSONReplacer(serializerOptions) : defaultReplacer
519
- ),
520
- deserialize: (payload, deserializerOptions) => JSON.parse(
521
- payload,
522
- deserializerOptions ? JSONReviver(deserializerOptions) : defaultReviver
523
- )
524
- };
525
- };
526
- var JSONSerializer = Object.assign(jsonSerializer(), {
527
- from: (options) => _nullishCoalesce(_optionalChain([options, 'optionalAccess', _14 => _14.serialization, 'optionalAccess', _15 => _15.serializer]), () => ( (_optionalChain([options, 'optionalAccess', _16 => _16.serialization, 'optionalAccess', _17 => _17.options]) ? jsonSerializer(_optionalChain([options, 'optionalAccess', _18 => _18.serialization, 'optionalAccess', _19 => _19.options])) : JSONSerializer)))
136
+ const documentsAreTheSame = (documents, options) => (assertOptions) => withCollection(async (collection) => {
137
+ const result = await collection.find("withId" in options ? { _id: options.withId } : options.matchingFilter);
138
+ (0, _event_driven_io_emmett.assertEqual)(documents.length, result.length, "Different Documents Count than expected");
139
+ for (let i = 0; i < documents.length; i++) (0, _event_driven_io_emmett.assertThatArray)(result).contains(documents[i]);
140
+ }, {
141
+ ...options,
142
+ ...assertOptions
528
143
  });
529
- var NoRetries = { retries: 0 };
530
- var asyncRetry = async (fn, opts) => {
531
- if (opts === void 0 || opts.retries === 0) return fn();
532
- return _asyncretry2.default.call(void 0,
533
- async (bail) => {
534
- try {
535
- const result = await fn();
536
- if (_optionalChain([opts, 'optionalAccess', _20 => _20.shouldRetryResult]) && opts.shouldRetryResult(result)) {
537
- throw new EmmettError(
538
- `Retrying because of result: ${JSONSerializer.serialize(result)}`
539
- );
540
- }
541
- return result;
542
- } catch (error) {
543
- if (_optionalChain([opts, 'optionalAccess', _21 => _21.shouldRetryError]) && !opts.shouldRetryError(error)) {
544
- bail(error);
545
- return void 0;
546
- }
547
- throw error;
548
- }
549
- },
550
- _nullishCoalesce(opts, () => ( { retries: 0 }))
551
- );
552
- };
553
- var onShutdown = (handler) => {
554
- const signals = ["SIGTERM", "SIGINT"];
555
- if (typeof process !== "undefined" && typeof process.on === "function") {
556
- for (const signal of signals) {
557
- process.on(signal, handler);
558
- }
559
- return () => {
560
- for (const signal of signals) {
561
- process.off(signal, handler);
562
- }
563
- };
564
- }
565
- const deno = globalThis.Deno;
566
- if (deno && typeof deno.addSignalListener === "function") {
567
- for (const signal of signals) {
568
- deno.addSignalListener(signal, handler);
569
- }
570
- return () => {
571
- for (const signal of signals) {
572
- deno.removeSignalListener(signal, handler);
573
- }
574
- };
575
- }
576
- return () => {
577
- };
578
- };
579
- var textEncoder = new TextEncoder();
580
- var getCheckpoint = (message2) => {
581
- return message2.metadata.checkpoint;
582
- };
583
- var wasMessageHandled = (message2, checkpoint) => {
584
- const messageCheckpoint = getCheckpoint(message2);
585
- return messageCheckpoint !== null && messageCheckpoint !== void 0 && checkpoint !== null && checkpoint !== void 0 && messageCheckpoint <= checkpoint;
586
- };
587
- var MessageProcessorType = {
588
- PROJECTOR: "projector",
589
- REACTOR: "reactor"
590
- };
591
- var defaultProcessingMessageProcessingScope = (handler, partialContext) => handler(partialContext);
592
- var bigIntProcessorCheckpoint = (value) => bigInt.toNormalizedString(value);
593
- var parseBigIntProcessorCheckpoint = (value) => BigInt(value);
594
- var defaultProcessorVersion = 1;
595
- var defaultProcessorPartition = defaultTag;
596
- var getProcessorInstanceId = (processorId) => `${processorId}:${_uuid.v7.call(void 0, )}`;
597
- var getProjectorId = (options) => `emt:processor:projector:${options.projectionName}`;
598
- var reactor = (options) => {
599
- const {
600
- checkpoints,
601
- processorId,
602
- processorInstanceId: instanceId = getProcessorInstanceId(processorId),
603
- type = MessageProcessorType.REACTOR,
604
- version = defaultProcessorVersion,
605
- partition = defaultProcessorPartition,
606
- hooks = {},
607
- processingScope = defaultProcessingMessageProcessingScope,
608
- startFrom,
609
- canHandle,
610
- stopAfter
611
- } = options;
612
- const eachMessage = "eachMessage" in options && options.eachMessage ? options.eachMessage : () => Promise.resolve();
613
- let isInitiated = false;
614
- let isActive = false;
615
- let lastCheckpoint = null;
616
- let closeSignal = null;
617
- const init = async (initOptions) => {
618
- if (isInitiated) return;
619
- if (hooks.onInit === void 0) {
620
- isInitiated = true;
621
- return;
622
- }
623
- return await processingScope(async (context) => {
624
- await hooks.onInit(context);
625
- isInitiated = true;
626
- }, initOptions);
627
- };
628
- const close = async (closeOptions) => {
629
- isActive = false;
630
- if (closeSignal) {
631
- closeSignal();
632
- closeSignal = null;
633
- }
634
- if (hooks.onClose) {
635
- await processingScope(hooks.onClose, closeOptions);
636
- }
637
- };
638
- return {
639
- // TODO: Consider whether not make it optional or add URN prefix
640
- id: processorId,
641
- instanceId,
642
- type,
643
- canHandle,
644
- init,
645
- start: async (startOptions) => {
646
- if (isActive) return;
647
- await init(startOptions);
648
- isActive = true;
649
- closeSignal = onShutdown(() => close(startOptions));
650
- if (lastCheckpoint !== null)
651
- return {
652
- lastCheckpoint
653
- };
654
- return await processingScope(async (context) => {
655
- if (hooks.onStart) {
656
- await hooks.onStart(context);
657
- }
658
- if (startFrom && startFrom !== "CURRENT") return startFrom;
659
- if (checkpoints) {
660
- const readResult = await _optionalChain([checkpoints, 'optionalAccess', _22 => _22.read, 'call', _23 => _23(
661
- {
662
- processorId,
663
- partition
664
- },
665
- { ...startOptions, ...context }
666
- )]);
667
- lastCheckpoint = readResult.lastCheckpoint;
668
- }
669
- if (lastCheckpoint === null) return "BEGINNING";
670
- return {
671
- lastCheckpoint
672
- };
673
- }, startOptions);
674
- },
675
- close,
676
- get isActive() {
677
- return isActive;
678
- },
679
- handle: async (messages, partialContext) => {
680
- if (!isActive) return Promise.resolve();
681
- 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(
686
- // TODO: Make it smarter
687
- message2,
688
- _optionalChain([options, 'access', _24 => _24.messageOptions, 'optionalAccess', _25 => _25.schema, 'optionalAccess', _26 => _26.versioning])
689
- );
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;
717
- }
718
- if (messageProcessingResult && messageProcessingResult.type === "SKIP")
719
- continue;
720
- }
721
- return result;
722
- }, partialContext);
723
- }
724
- };
725
- };
726
- var projector = (options) => {
727
- const {
728
- projection: projection2,
729
- processorId = getProjectorId({
730
- projectionName: _nullishCoalesce(projection2.name, () => ( "unknown"))
731
- }),
732
- ...rest
733
- } = options;
734
- return reactor({
735
- ...rest,
736
- type: MessageProcessorType.PROJECTOR,
737
- canHandle: projection2.canHandle,
738
- processorId,
739
- messageOptions: options.projection.eventsOptions,
740
- 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) => {
743
- if (options.truncateOnStart && options.projection.truncate)
744
- 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)]);
746
- } : void 0,
747
- onClose: _optionalChain([options, 'access', _36 => _36.hooks, 'optionalAccess', _37 => _37.onClose])
748
- },
749
- eachMessage: async (event2, context) => projection2.handle([event2], context)
750
- });
751
- };
752
- var AssertionError = class extends Error {
753
- constructor(message2) {
754
- super(message2);
755
- }
756
- };
757
- var isSubset = (superObj, subObj) => {
758
- const sup = superObj;
759
- const sub = subObj;
760
- assertOk(sup);
761
- assertOk(sub);
762
- return Object.keys(sub).every((ele) => {
763
- if (sub[ele] !== null && typeof sub[ele] == "object") {
764
- return isSubset(sup[ele], sub[ele]);
765
- }
766
- return sub[ele] === sup[ele];
767
- });
768
- };
769
- var assertFails = (message2) => {
770
- throw new AssertionError(_nullishCoalesce(message2, () => ( "That should not ever happened, right?")));
771
- };
772
- var assertDeepEqual = (actual, expected, message2) => {
773
- if (!deepEquals(actual, expected))
774
- throw new AssertionError(
775
- _nullishCoalesce(message2, () => ( `subObj:
776
- ${JSONSerializer.serialize(expected)}
777
- is not equal to
778
- ${JSONSerializer.serialize(actual)}`))
779
- );
780
- };
781
- function assertTrue(condition, message2) {
782
- if (condition !== true)
783
- throw new AssertionError(_nullishCoalesce(message2, () => ( `Condition is false`)));
784
- }
785
- function assertOk(obj, message2) {
786
- if (!obj) throw new AssertionError(_nullishCoalesce(message2, () => ( `Condition is not truthy`)));
787
- }
788
- function assertEqual(expected, actual, message2) {
789
- if (expected !== actual)
790
- throw new AssertionError(
791
- `${_nullishCoalesce(message2, () => ( "Objects are not equal"))}:
792
- Expected: ${JSONSerializer.serialize(expected)}
793
- Actual: ${JSONSerializer.serialize(actual)}`
794
- );
795
- }
796
- function assertNotEqual(obj, other, message2) {
797
- if (obj === other)
798
- throw new AssertionError(
799
- _nullishCoalesce(message2, () => ( `Objects are equal: ${JSONSerializer.serialize(obj)}`))
800
- );
801
- }
802
- function assertIsNotNull(result) {
803
- assertNotEqual(result, null);
804
- assertOk(result);
805
- }
806
- function assertIsNull(result) {
807
- assertEqual(result, null);
808
- }
809
- var assertThatArray = (array) => {
810
- return {
811
- isEmpty: () => assertEqual(
812
- array.length,
813
- 0,
814
- `Array is not empty ${JSONSerializer.serialize(array)}`
815
- ),
816
- isNotEmpty: () => assertNotEqual(array.length, 0, `Array is empty`),
817
- hasSize: (length) => assertEqual(array.length, length),
818
- containsElements: (other) => {
819
- assertTrue(other.every((ts) => array.some((o) => deepEquals(ts, o))));
820
- },
821
- containsElementsMatching: (other) => {
822
- assertTrue(other.every((ts) => array.some((o) => isSubset(o, ts))));
823
- },
824
- containsOnlyElementsMatching: (other) => {
825
- assertEqual(array.length, other.length, `Arrays lengths don't match`);
826
- assertTrue(other.every((ts) => array.some((o) => isSubset(o, ts))));
827
- },
828
- containsExactlyInAnyOrder: (other) => {
829
- assertEqual(array.length, other.length);
830
- assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));
831
- },
832
- containsExactlyInAnyOrderElementsOf: (other) => {
833
- assertEqual(array.length, other.length);
834
- assertTrue(array.every((ts) => other.some((o) => deepEquals(ts, o))));
835
- },
836
- containsExactlyElementsOf: (other) => {
837
- assertEqual(array.length, other.length);
838
- for (let i = 0; i < array.length; i++) {
839
- assertTrue(deepEquals(array[i], other[i]));
840
- }
841
- },
842
- containsExactly: (elem) => {
843
- assertEqual(array.length, 1);
844
- assertTrue(deepEquals(array[0], elem));
845
- },
846
- contains: (elem) => {
847
- assertTrue(array.some((a) => deepEquals(a, elem)));
848
- },
849
- containsOnlyOnceElementsOf: (other) => {
850
- assertTrue(
851
- other.map((o) => array.filter((a) => deepEquals(a, o)).length).filter((a) => a === 1).length === other.length
852
- );
853
- },
854
- containsAnyOf: (other) => {
855
- assertTrue(array.some((a) => other.some((o) => deepEquals(a, o))));
856
- },
857
- allMatch: (matches) => {
858
- assertTrue(array.every(matches));
859
- },
860
- anyMatches: (matches) => {
861
- assertTrue(array.some(matches));
862
- },
863
- allMatchAsync: async (matches) => {
864
- for (const item of array) {
865
- assertTrue(await matches(item));
866
- }
867
- }
868
- };
869
- };
870
- var downcastRecordedMessage = (recordedMessage, options) => {
871
- if (!_optionalChain([options, 'optionalAccess', _38 => _38.downcast]))
872
- return recordedMessage;
873
- const downcasted = options.downcast(
874
- recordedMessage
875
- );
876
- return {
877
- ...recordedMessage,
878
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
879
- data: downcasted.data,
880
- ..."metadata" in recordedMessage || "metadata" in downcasted ? {
881
- metadata: {
882
- ..."metadata" in recordedMessage ? recordedMessage.metadata : {},
883
- ..."metadata" in downcasted ? downcasted.metadata : {}
884
- }
885
- } : {}
886
- };
887
- };
888
- var downcastRecordedMessages = (recordedMessages, options) => {
889
- if (!_optionalChain([options, 'optionalAccess', _39 => _39.downcast]))
890
- return recordedMessages;
891
- return recordedMessages.map(
892
- (recordedMessage) => downcastRecordedMessage(recordedMessage, options)
893
- );
894
- };
895
- var upcastRecordedMessage = (recordedMessage, options) => {
896
- if (!_optionalChain([options, 'optionalAccess', _40 => _40.upcast]))
897
- return recordedMessage;
898
- const upcasted = options.upcast(
899
- recordedMessage
900
- );
901
- return {
902
- ...recordedMessage,
903
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
904
- data: upcasted.data,
905
- ..."metadata" in recordedMessage || "metadata" in upcasted ? {
906
- metadata: {
907
- ..."metadata" in recordedMessage ? recordedMessage.metadata : {},
908
- ..."metadata" in upcasted ? upcasted.metadata : {}
909
- }
910
- } : {}
911
- };
912
- };
913
- var projection = (definition) => definition;
914
- var WorkflowHandlerStreamVersionConflictRetryOptions = {
915
- retries: 3,
916
- minTimeout: 100,
917
- factor: 1.5,
918
- shouldRetryError: isExpectedVersionConflictError
919
- };
920
- var fromWorkflowHandlerRetryOptions = (retryOptions) => {
921
- if (retryOptions === void 0) return NoRetries;
922
- if ("onVersionConflict" in retryOptions) {
923
- if (typeof retryOptions.onVersionConflict === "boolean")
924
- return WorkflowHandlerStreamVersionConflictRetryOptions;
925
- else if (typeof retryOptions.onVersionConflict === "number")
926
- return {
927
- ...WorkflowHandlerStreamVersionConflictRetryOptions,
928
- retries: retryOptions.onVersionConflict
929
- };
930
- else return retryOptions.onVersionConflict;
931
- }
932
- return retryOptions;
933
- };
934
- var emptyHandlerResult = (nextExpectedStreamVersion = 0n) => ({
935
- newMessages: [],
936
- createdNewStream: false,
937
- nextExpectedStreamVersion
144
+ const documentsMatchingHaveCount = (expectedCount, options) => (assertOptions) => withCollection(async (collection) => {
145
+ (0, _event_driven_io_emmett.assertEqual)(expectedCount, (await collection.find("withId" in options ? { _id: options.withId } : options.matchingFilter)).length, "Different Documents Count than expected");
146
+ }, {
147
+ ...options,
148
+ ...assertOptions
938
149
  });
939
- var createInputMetadata = (originalMessageId, action) => ({
940
- originalMessageId,
941
- input: true,
942
- action
150
+ const documentMatchingExists = (options) => (assertOptions) => withCollection(async (collection) => {
151
+ (0, _event_driven_io_emmett.assertThatArray)(await collection.find("withId" in options ? { _id: options.withId } : options.matchingFilter)).isNotEmpty();
152
+ }, {
153
+ ...options,
154
+ ...assertOptions
943
155
  });
944
- var tagOutputMessage = (msg, action) => {
945
- const existingMetadata = "metadata" in msg && msg.metadata ? msg.metadata : {};
946
- return {
947
- ...msg,
948
- metadata: {
949
- ...existingMetadata,
950
- action
951
- }
952
- };
953
- };
954
- var createWrappedInitialState = (initialState) => {
955
- return () => ({
956
- userState: initialState(),
957
- processedInputIds: /* @__PURE__ */ new Set()
958
- });
959
- };
960
- var createWrappedEvolve = (evolve, workflowName, separateInputInboxFromProcessing) => {
961
- return (state, event2) => {
962
- const metadata = event2.metadata;
963
- let processedInputIds = state.processedInputIds;
964
- if (_optionalChain([metadata, 'optionalAccess', _41 => _41.input]) === true && typeof _optionalChain([metadata, 'optionalAccess', _42 => _42.originalMessageId]) === "string") {
965
- processedInputIds = new Set(state.processedInputIds);
966
- processedInputIds.add(metadata.originalMessageId);
967
- }
968
- if (separateInputInboxFromProcessing && _optionalChain([metadata, 'optionalAccess', _43 => _43.input]) === true) {
969
- return {
970
- userState: state.userState,
971
- processedInputIds
972
- };
973
- }
974
- const eventType = event2.type;
975
- const eventForEvolve = eventType.startsWith(`${workflowName}:`) ? {
976
- ...event2,
977
- type: eventType.replace(`${workflowName}:`, "")
978
- } : event2;
979
- return {
980
- userState: evolve(state.userState, eventForEvolve),
981
- processedInputIds
982
- };
983
- };
984
- };
985
- var workflowStreamName = ({
986
- workflowName,
987
- workflowId
988
- }) => `emt:workflow:${workflowName}:${workflowId}`;
989
- var WorkflowHandler = (options) => async (store, message2, handleOptions) => asyncRetry(
990
- async () => {
991
- const result = await withSession2(store, async ({ eventStore }) => {
992
- const {
993
- workflow: { evolve, initialState, decide, name: workflowName },
994
- getWorkflowId: getWorkflowId2
995
- } = options;
996
- const inputMessageId = (
997
- // 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]) ? (
999
- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
1000
- message2.metadata.messageId
1001
- ) : void 0), () => ( _uuid.v7.call(void 0, )))
1002
- );
1003
- const messageWithMetadata = {
1004
- ...message2,
1005
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1006
- metadata: {
1007
- messageId: inputMessageId,
1008
- ...message2.metadata
1009
- }
1010
- };
1011
- const workflowId = getWorkflowId2(messageWithMetadata);
1012
- if (!workflowId) {
1013
- return emptyHandlerResult();
1014
- }
1015
- const streamName = options.mapWorkflowId ? options.mapWorkflowId(workflowId) : workflowStreamName({ workflowName, workflowId });
1016
- const messageType = messageWithMetadata.type;
1017
- const hasWorkflowPrefix = messageType.startsWith(`${workflowName}:`);
1018
- if (options.separateInputInboxFromProcessing && !hasWorkflowPrefix) {
1019
- const inputMetadata2 = createInputMetadata(
1020
- inputMessageId,
1021
- "InitiatedBy"
1022
- );
1023
- const inputToStore2 = {
1024
- type: `${workflowName}:${messageWithMetadata.type}`,
1025
- data: messageWithMetadata.data,
1026
- kind: messageWithMetadata.kind,
1027
- metadata: inputMetadata2
1028
- };
1029
- const appendResult2 = await eventStore.appendToStream(
1030
- streamName,
1031
- [inputToStore2],
1032
- {
1033
- ...handleOptions,
1034
- expectedStreamVersion: _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _46 => _46.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1035
- }
1036
- );
1037
- return {
1038
- ...appendResult2,
1039
- newMessages: []
1040
- };
1041
- }
1042
- const wrappedInitialState = createWrappedInitialState(initialState);
1043
- const wrappedEvolve = createWrappedEvolve(
1044
- evolve,
1045
- workflowName,
1046
- _nullishCoalesce(options.separateInputInboxFromProcessing, () => ( false))
1047
- );
1048
- const aggregationResult = await eventStore.aggregateStream(streamName, {
1049
- evolve: wrappedEvolve,
1050
- initialState: wrappedInitialState,
1051
- read: {
1052
- ...handleOptions,
1053
- // expected stream version is passed to fail fast
1054
- // if stream is in the wrong state
1055
- expectedStreamVersion: _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _47 => _47.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
1056
- }
1057
- });
1058
- const { currentStreamVersion } = aggregationResult;
1059
- const { userState: state, processedInputIds } = aggregationResult.state;
1060
- if (processedInputIds.has(inputMessageId)) {
1061
- return emptyHandlerResult(currentStreamVersion);
1062
- }
1063
- const messageForDecide = hasWorkflowPrefix ? {
1064
- ...messageWithMetadata,
1065
- type: messageType.replace(`${workflowName}:`, "")
1066
- } : messageWithMetadata;
1067
- const result2 = decide(messageForDecide, state);
1068
- const inputMetadata = createInputMetadata(
1069
- inputMessageId,
1070
- aggregationResult.streamExists ? "Received" : "InitiatedBy"
1071
- );
1072
- const inputToStore = {
1073
- type: `${workflowName}:${messageWithMetadata.type}`,
1074
- data: messageWithMetadata.data,
1075
- kind: messageWithMetadata.kind,
1076
- metadata: inputMetadata
1077
- };
1078
- 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]), () => ( []));
1080
- const taggedOutputMessages = outputMessages.map((msg) => {
1081
- const action = outputCommandTypes.includes(
1082
- msg.type
1083
- ) ? "Sent" : "Published";
1084
- return tagOutputMessage(msg, action);
1085
- });
1086
- const messagesToAppend = options.separateInputInboxFromProcessing && hasWorkflowPrefix ? [...taggedOutputMessages] : [inputToStore, ...taggedOutputMessages];
1087
- if (messagesToAppend.length === 0) {
1088
- return emptyHandlerResult(currentStreamVersion);
1089
- }
1090
- const expectedStreamVersion = _nullishCoalesce(_optionalChain([handleOptions, 'optionalAccess', _50 => _50.expectedStreamVersion]), () => ( (aggregationResult.streamExists ? currentStreamVersion : STREAM_DOES_NOT_EXIST)));
1091
- const appendResult = await eventStore.appendToStream(
1092
- streamName,
1093
- // TODO: Fix this cast
1094
- messagesToAppend,
1095
- {
1096
- ...handleOptions,
1097
- expectedStreamVersion
1098
- }
1099
- );
1100
- return {
1101
- ...appendResult,
1102
- newMessages: outputMessages
1103
- };
1104
- });
1105
- return result;
1106
- },
1107
- fromWorkflowHandlerRetryOptions(
1108
- handleOptions && "retry" in handleOptions ? handleOptions.retry : options.retry
1109
- )
1110
- );
1111
- var withSession2 = (eventStore, callback) => {
1112
- const sessionFactory = canCreateEventStoreSession(eventStore) ? eventStore : nulloSessionFactory(eventStore);
1113
- return sessionFactory.withSession(callback);
1114
- };
1115
- var getWorkflowId = (options) => `emt:processor:workflow:${options.workflowName}`;
1116
- var workflowProcessor = (options) => {
1117
- const { workflow, ...rest } = options;
1118
- const inputs = [...options.inputs.commands, ...options.inputs.events];
1119
- let canHandle = inputs;
1120
- if (options.separateInputInboxFromProcessing)
1121
- canHandle = [
1122
- ...canHandle,
1123
- ...options.inputs.commands.map((t) => `${workflow.name}:${t}`),
1124
- ...options.inputs.events.map((t) => `${workflow.name}:${t}`)
1125
- ];
1126
- if (options.outputHandler)
1127
- canHandle = [...canHandle, ...options.outputHandler.canHandle];
1128
- const handle = WorkflowHandler(options);
1129
- return reactor({
1130
- ...rest,
1131
- processorId: _nullishCoalesce(options.processorId, () => ( getWorkflowId({ workflowName: workflow.name }))),
1132
- canHandle,
1133
- type: MessageProcessorType.PROJECTOR,
1134
- eachMessage: async (message2, context) => {
1135
- const messageType = message2.type;
1136
- const metadata = message2.metadata;
1137
- const isInput = _optionalChain([metadata, 'optionalAccess', _51 => _51.input]) === true;
1138
- if (isInput || inputs.includes(messageType)) {
1139
- const result = await handle(
1140
- context.connection.messageStore,
1141
- message2,
1142
- context
1143
- );
1144
- if (options.stopAfter && result.newMessages.length > 0) {
1145
- for (const outputMessage of result.newMessages) {
1146
- if (options.stopAfter(
1147
- outputMessage
1148
- )) {
1149
- return { type: "STOP", reason: "Stop condition reached" };
1150
- }
1151
- }
1152
- }
1153
- return;
1154
- }
1155
- if (_optionalChain([options, 'access', _52 => _52.outputHandler, 'optionalAccess', _53 => _53.canHandle, 'access', _54 => _54.includes, 'call', _55 => _55(messageType)]) === true) {
1156
- const recordedMessage = message2;
1157
- const handledOutputMessages = options.outputHandler.eachBatch ? await options.outputHandler.eachBatch([recordedMessage], context) : await options.outputHandler.eachMessage(recordedMessage, context);
1158
- if (handledOutputMessages instanceof EmmettError) {
1159
- return {
1160
- type: "STOP",
1161
- reason: "Routing error",
1162
- error: handledOutputMessages
1163
- };
1164
- }
1165
- const messagesToAppend = Array.isArray(handledOutputMessages) ? handledOutputMessages : handledOutputMessages ? [handledOutputMessages] : [];
1166
- if (messagesToAppend.length === 0) {
1167
- return;
1168
- }
1169
- const workflowId = options.getWorkflowId(
1170
- message2
1171
- );
1172
- if (!workflowId) return;
1173
- const streamName = options.mapWorkflowId ? options.mapWorkflowId(workflowId) : workflowStreamName({
1174
- workflowName: workflow.name,
1175
- workflowId
1176
- });
1177
- await context.connection.messageStore.appendToStream(
1178
- streamName,
1179
- messagesToAppend
1180
- );
1181
- return;
1182
- }
1183
- return;
1184
- }
1185
- });
1186
- };
1187
-
1188
- // src/eventStore/projections/pongo/pongoProjectionSpec.ts
1189
-
1190
-
1191
-
1192
- var withCollection = async (handle, options) => {
1193
- const { connection, inDatabase, inCollection } = options;
1194
- const driver = await pongoDriverRegistry.tryResolve(
1195
- connection.driverType
1196
- );
1197
- const pongo = _pongo.pongoClient.call(void 0, {
1198
- connectionOptions: { connection },
1199
- driver
1200
- });
1201
- try {
1202
- const collection = pongo.db(inDatabase).collection(inCollection);
1203
- return handle(collection);
1204
- } finally {
1205
- await pongo.close();
1206
- }
1207
- };
1208
- var withoutIdAndVersion = (doc) => {
1209
- const { _id, _version, ...without } = doc;
1210
- return without;
1211
- };
1212
- var assertDocumentsEqual = (actual, expected) => {
1213
- if ("_id" in expected)
1214
- assertEqual(
1215
- expected._id,
1216
- actual._id,
1217
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
1218
- `Document ids are not matching! Expected: ${expected._id}, Actual: ${actual._id}`
1219
- );
1220
- return assertDeepEqual(
1221
- withoutIdAndVersion(actual),
1222
- withoutIdAndVersion(expected)
1223
- );
1224
- };
1225
- var documentExists = (document, options) => (assertOptions) => withCollection(
1226
- async (collection) => {
1227
- const result = await collection.findOne(
1228
- "withId" in options ? { _id: options.withId } : options.matchingFilter
1229
- );
1230
- assertIsNotNull(result);
1231
- assertDocumentsEqual(result, document);
1232
- },
1233
- { ...options, ...assertOptions }
1234
- );
1235
- var documentsAreTheSame = (documents, options) => (assertOptions) => withCollection(
1236
- async (collection) => {
1237
- const result = await collection.find(
1238
- "withId" in options ? { _id: options.withId } : options.matchingFilter
1239
- );
1240
- assertEqual(
1241
- documents.length,
1242
- result.length,
1243
- "Different Documents Count than expected"
1244
- );
1245
- for (let i = 0; i < documents.length; i++) {
1246
- assertThatArray(result).contains(documents[i]);
1247
- }
1248
- },
1249
- { ...options, ...assertOptions }
1250
- );
1251
- var documentsMatchingHaveCount = (expectedCount, options) => (assertOptions) => withCollection(
1252
- async (collection) => {
1253
- const result = await collection.find(
1254
- "withId" in options ? { _id: options.withId } : options.matchingFilter
1255
- );
1256
- assertEqual(
1257
- expectedCount,
1258
- result.length,
1259
- "Different Documents Count than expected"
1260
- );
1261
- },
1262
- { ...options, ...assertOptions }
1263
- );
1264
- var documentMatchingExists = (options) => (assertOptions) => withCollection(
1265
- async (collection) => {
1266
- const result = await collection.find(
1267
- "withId" in options ? { _id: options.withId } : options.matchingFilter
1268
- );
1269
- assertThatArray(result).isNotEmpty();
1270
- },
1271
- { ...options, ...assertOptions }
1272
- );
1273
- var documentDoesNotExist = (options) => (assertOptions) => withCollection(
1274
- async (collection) => {
1275
- const result = await collection.findOne(
1276
- "withId" in options ? { _id: options.withId } : options.matchingFilter
1277
- );
1278
- assertIsNull(result);
1279
- },
1280
- { ...options, ...assertOptions }
1281
- );
1282
- var expectPongoDocuments = {
1283
- fromCollection: (collectionName) => {
1284
- return {
1285
- withId: (id) => {
1286
- return {
1287
- toBeEqual: (document) => documentExists(document, {
1288
- withId: id,
1289
- inCollection: collectionName
1290
- }),
1291
- toExist: () => documentMatchingExists({
1292
- withId: id,
1293
- inCollection: collectionName
1294
- }),
1295
- notToExist: () => documentDoesNotExist({
1296
- withId: id,
1297
- inCollection: collectionName
1298
- })
1299
- };
1300
- },
1301
- matching: (filter) => {
1302
- return {
1303
- toBeTheSame: (documents) => documentsAreTheSame(documents, {
1304
- matchingFilter: filter,
1305
- inCollection: collectionName
1306
- }),
1307
- toHaveCount: (expectedCount) => documentsMatchingHaveCount(expectedCount, {
1308
- matchingFilter: filter,
1309
- inCollection: collectionName
1310
- }),
1311
- toExist: () => documentMatchingExists({
1312
- matchingFilter: filter,
1313
- inCollection: collectionName
1314
- }),
1315
- notToExist: () => documentDoesNotExist({
1316
- matchingFilter: filter,
1317
- inCollection: collectionName
1318
- })
1319
- };
1320
- }
1321
- };
1322
- }
1323
- };
1324
-
1325
- // src/eventStore/projections/sqliteProjection.ts
1326
- var handleProjections = async (options) => {
1327
- const {
1328
- projections: allProjections,
1329
- events,
1330
- connection,
1331
- execute,
1332
- driverType
1333
- } = options;
1334
- const eventTypes = events.map((e) => e.type);
1335
- for (const projection2 of allProjections) {
1336
- if (!projection2.canHandle.some((type) => eventTypes.includes(type))) {
1337
- continue;
1338
- }
1339
- await projection2.handle(events, {
1340
- connection,
1341
- execute,
1342
- driverType
1343
- });
1344
- }
1345
- };
1346
- var sqliteProjection = (definition) => projection(definition);
1347
- var sqliteRawBatchSQLProjection = (options) => sqliteProjection({
1348
- name: options.name,
1349
- kind: _nullishCoalesce(options.kind, () => ( "emt:projections:sqlite:raw_sql:batch")),
1350
- version: options.version,
1351
- canHandle: options.canHandle,
1352
- eventsOptions: options.eventsOptions,
1353
- handle: async (events, context) => {
1354
- const sqls = await options.evolve(events, context);
1355
- await context.execute.batchCommand(sqls);
1356
- },
1357
- init: async (initOptions) => {
1358
- const initSQL = options.init ? await options.init(initOptions) : void 0;
1359
- if (initSQL) {
1360
- if (Array.isArray(initSQL)) {
1361
- await initOptions.context.execute.batchCommand(initSQL);
1362
- } else {
1363
- await initOptions.context.execute.command(initSQL);
1364
- }
1365
- }
1366
- }
156
+ const documentDoesNotExist = (options) => (assertOptions) => withCollection(async (collection) => {
157
+ (0, _event_driven_io_emmett.assertIsNull)(await collection.findOne("withId" in options ? { _id: options.withId } : options.matchingFilter));
158
+ }, {
159
+ ...options,
160
+ ...assertOptions
1367
161
  });
1368
- var sqliteRawSQLProjection = (options) => {
1369
- const { evolve, kind, ...rest } = options;
1370
- return sqliteRawBatchSQLProjection({
1371
- kind: _nullishCoalesce(kind, () => ( "emt:projections:sqlite:raw:_sql:single")),
1372
- ...rest,
1373
- evolve: async (events, context) => {
1374
- const sqls = [];
1375
- for (const event of events) {
1376
- const pendingSqls = await evolve(event, context);
1377
- if (Array.isArray(pendingSqls)) {
1378
- sqls.push(...pendingSqls);
1379
- } else {
1380
- sqls.push(pendingSqls);
1381
- }
1382
- }
1383
- return sqls;
1384
- }
1385
- });
1386
- };
1387
-
1388
- // src/eventStore/projections/sqliteProjectionSpec.ts
1389
- var _dumbo = require('@event-driven-io/dumbo');
1390
-
1391
- var SQLiteProjectionSpec = {
1392
- for: (options) => {
1393
- {
1394
- const driverType = options.driver.driverType;
1395
- const pool = _nullishCoalesce(options.pool, () => ( _dumbo.dumbo.call(void 0, {
1396
- serialization: options.serialization,
1397
- transactionOptions: {
1398
- allowNestedTransactions: true,
1399
- mode: "session_based"
1400
- },
1401
- ...options.driver.mapToDumboOptions(options)
1402
- })));
1403
- const projection2 = options.projection;
1404
- let wasInitialized = false;
1405
- return (givenEvents) => {
1406
- return {
1407
- when: (events, options2) => {
1408
- const allEvents = [];
1409
- const run = async (connection) => {
1410
- let globalPosition = 0n;
1411
- const numberOfTimes = _nullishCoalesce(_optionalChain([options2, 'optionalAccess', _56 => _56.numberOfTimes]), () => ( 1));
1412
- for (const event of [
1413
- ...givenEvents,
1414
- ...Array.from({ length: numberOfTimes }).flatMap(() => events)
1415
- ]) {
1416
- const metadata = {
1417
- checkpoint: bigIntProcessorCheckpoint(++globalPosition),
1418
- globalPosition,
1419
- streamPosition: globalPosition,
1420
- streamName: `test-${_uuid.v4.call(void 0, )}`,
1421
- messageId: _uuid.v4.call(void 0, )
1422
- };
1423
- allEvents.push({
1424
- ...event,
1425
- kind: "Event",
1426
- metadata: {
1427
- ...metadata,
1428
- ..."metadata" in event ? _nullishCoalesce(event.metadata, () => ( {})) : {}
1429
- }
1430
- });
1431
- }
1432
- if (!wasInitialized && projection2.init) {
1433
- await projection2.init({
1434
- registrationType: "async",
1435
- status: "active",
1436
- context: {
1437
- execute: connection.execute,
1438
- connection,
1439
- driverType
1440
- },
1441
- version: _nullishCoalesce(projection2.version, () => ( 1))
1442
- });
1443
- wasInitialized = true;
1444
- }
1445
- await connection.withTransaction(
1446
- () => handleProjections({
1447
- events: allEvents,
1448
- projections: [projection2],
1449
- execute: connection.execute,
1450
- connection,
1451
- driverType
1452
- })
1453
- );
1454
- };
1455
- return {
1456
- then: (assert, message) => pool.withConnection(async (connection) => {
1457
- await run(connection);
1458
- const succeeded = await assert({
1459
- connection
1460
- });
1461
- if (succeeded !== void 0 && succeeded === false)
1462
- assertFails(
1463
- _nullishCoalesce(message, () => ( "Projection specification didn't match the criteria"))
1464
- );
1465
- }),
1466
- thenThrows: (...args) => pool.withConnection(async (connection) => {
1467
- try {
1468
- await run(connection);
1469
- throw new AssertionError(
1470
- "Handler did not fail as expected"
1471
- );
1472
- } catch (error) {
1473
- if (error instanceof AssertionError) throw error;
1474
- if (args.length === 0) return;
1475
- if (!isErrorConstructor(args[0])) {
1476
- assertTrue(
1477
- args[0](error),
1478
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _57 => _57.toString, 'call', _58 => _58()])}`
1479
- );
1480
- return;
1481
- }
1482
- assertTrue(
1483
- error instanceof args[0],
1484
- `Caught error is not an instance of the expected type: ${_optionalChain([error, 'optionalAccess', _59 => _59.toString, 'call', _60 => _60()])}`
1485
- );
1486
- if (args[1]) {
1487
- assertTrue(
1488
- args[1](error),
1489
- `Error didn't match the error condition: ${_optionalChain([error, 'optionalAccess', _61 => _61.toString, 'call', _62 => _62()])}`
1490
- );
1491
- }
1492
- }
1493
- })
1494
- };
1495
- }
1496
- };
1497
- };
1498
- }
1499
- }
1500
- };
1501
- var eventInStream = (streamName, event) => {
1502
- return {
1503
- ...event,
1504
- metadata: {
1505
- ..._nullishCoalesce(event.metadata, () => ( {})),
1506
- streamName: _nullishCoalesce(_optionalChain([event, 'access', _63 => _63.metadata, 'optionalAccess', _64 => _64.streamName]), () => ( streamName))
1507
- }
1508
- };
1509
- };
1510
- var eventsInStream = (streamName, events) => {
1511
- return events.map((e) => eventInStream(streamName, e));
1512
- };
1513
- var newEventsInStream = eventsInStream;
1514
- var assertSQLQueryResultMatches = (sql, rows) => async ({
1515
- connection
1516
- }) => {
1517
- const result = await connection.execute.query(sql);
1518
- assertThatArray(rows).containsExactlyInAnyOrder(result.rows);
1519
- };
1520
- var expectSQL = {
1521
- query: (sql) => ({
1522
- resultRows: {
1523
- toBeTheSame: (rows) => assertSQLQueryResultMatches(sql, rows)
1524
- }
1525
- })
1526
- };
1527
-
1528
- // src/eventStore/schema/appendToStream.ts
1529
-
1530
-
1531
-
1532
-
1533
-
1534
-
1535
-
1536
-
1537
-
1538
- // src/eventStore/schema/typing.ts
1539
- var emmettPrefix2 = "emt";
1540
- var globalTag = "global";
1541
- var defaultTag2 = `${emmettPrefix2}:default`;
1542
- var unknownTag2 = `${emmettPrefix2}:unknown`;
1543
- var globalNames = {
1544
- module: `${emmettPrefix2}:module:${globalTag}`
1545
- };
1546
- var columns = {
1547
- partition: {
1548
- name: "partition"
1549
- },
1550
- isArchived: { name: "is_archived" }
1551
- };
1552
- var streamsTable = {
1553
- name: `${emmettPrefix2}_streams`,
1554
- columns: {
1555
- partition: columns.partition,
1556
- isArchived: columns.isArchived
1557
- }
1558
- };
1559
- var messagesTable = {
1560
- name: `${emmettPrefix2}_messages`,
1561
- columns: {
1562
- partition: columns.partition,
1563
- isArchived: columns.isArchived
1564
- }
1565
- };
1566
- var processorsTable = {
1567
- name: `${emmettPrefix2}_processors`
1568
- };
1569
- var projectionsTable = {
1570
- name: `${emmettPrefix2}_projections`
1571
- };
1572
-
1573
- // src/eventStore/schema/appendToStream.ts
1574
- var { identifier, merge } = _dumbo.SQL;
1575
- var appendToStream = async (connection, streamName, streamType, messages, options) => {
1576
- if (messages.length === 0) return { success: false };
1577
- const expectedStreamVersion = toExpectedVersion(
1578
- _optionalChain([options, 'optionalAccess', _65 => _65.expectedStreamVersion])
1579
- );
1580
- const messagesToAppend = messages.map(
1581
- (m, i) => ({
1582
- ...m,
1583
- kind: _nullishCoalesce(m.kind, () => ( "Event")),
1584
- metadata: {
1585
- streamName,
1586
- messageId: _uuid.v4.call(void 0, ),
1587
- streamPosition: BigInt(i + 1),
1588
- ..."metadata" in m ? _nullishCoalesce(m.metadata, () => ( {})) : {}
1589
- }
1590
- })
1591
- );
1592
- try {
1593
- return await connection.withTransaction(
1594
- async (transaction) => {
1595
- const result = await appendToStreamRaw(
1596
- transaction.execute,
1597
- streamName,
1598
- streamType,
1599
- downcastRecordedMessages(
1600
- messagesToAppend,
1601
- _optionalChain([options, 'optionalAccess', _66 => _66.schema, 'optionalAccess', _67 => _67.versioning])
1602
- ),
1603
- {
1604
- expectedStreamVersion
1605
- }
1606
- );
1607
- if (_optionalChain([options, 'optionalAccess', _68 => _68.onBeforeCommit]))
1608
- await options.onBeforeCommit(messagesToAppend, { connection });
1609
- return { success: true, result };
1610
- }
1611
- );
1612
- } catch (err) {
1613
- if (isExpectedVersionConflictError(err) || _dumbo.DumboError.isInstanceOf(err, {
1614
- errorType: _dumbo.UniqueConstraintError.ErrorType
1615
- }) || _dumbo.DumboError.isInstanceOf(err, {
1616
- errorType: _dumbo.BatchCommandNoChangesError.ErrorType
1617
- })) {
1618
- return { success: false };
1619
- }
1620
- throw err;
1621
- }
1622
- };
1623
- var toExpectedVersion = (expected) => {
1624
- if (expected === void 0) return null;
1625
- if (expected === NO_CONCURRENCY_CHECK) return null;
1626
- if (expected == STREAM_DOES_NOT_EXIST) return null;
1627
- if (expected == STREAM_EXISTS) return null;
1628
- return expected;
1629
- };
1630
- var appendToStreamRaw = async (execute, streamId, streamType, messages, options) => {
1631
- let expectedStreamVersion = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _69 => _69.expectedStreamVersion]), () => ( null));
1632
- const currentStreamVersion = await getLastStreamPosition(
1633
- execute,
1634
- streamId,
1635
- expectedStreamVersion
1636
- );
1637
- expectedStreamVersion ??= _nullishCoalesce(currentStreamVersion, () => ( 0n));
1638
- if (expectedStreamVersion !== currentStreamVersion) {
1639
- throw new ExpectedVersionConflictError(
1640
- currentStreamVersion,
1641
- expectedStreamVersion
1642
- );
1643
- }
1644
- const streamSQL = expectedStreamVersion === 0n ? _dumbo.SQL`INSERT INTO ${identifier(streamsTable.name)}
162
+ const expectPongoDocuments = { fromCollection: (collectionName) => {
163
+ return {
164
+ withId: (id) => {
165
+ return {
166
+ toBeEqual: (document) => documentExists(document, {
167
+ withId: id,
168
+ inCollection: collectionName
169
+ }),
170
+ toExist: () => documentMatchingExists({
171
+ withId: id,
172
+ inCollection: collectionName
173
+ }),
174
+ notToExist: () => documentDoesNotExist({
175
+ withId: id,
176
+ inCollection: collectionName
177
+ })
178
+ };
179
+ },
180
+ matching: (filter) => {
181
+ return {
182
+ toBeTheSame: (documents) => documentsAreTheSame(documents, {
183
+ matchingFilter: filter,
184
+ inCollection: collectionName
185
+ }),
186
+ toHaveCount: (expectedCount) => documentsMatchingHaveCount(expectedCount, {
187
+ matchingFilter: filter,
188
+ inCollection: collectionName
189
+ }),
190
+ toExist: () => documentMatchingExists({
191
+ matchingFilter: filter,
192
+ inCollection: collectionName
193
+ }),
194
+ notToExist: () => documentDoesNotExist({
195
+ matchingFilter: filter,
196
+ inCollection: collectionName
197
+ })
198
+ };
199
+ }
200
+ };
201
+ } };
202
+
203
+ //#endregion
204
+ //#region src/eventStore/projections/sqliteProjection.ts
205
+ const handleProjections = async (options) => {
206
+ const { projections: allProjections, events, connection, execute, driverType } = options;
207
+ const eventTypes = events.map((e) => e.type);
208
+ for (const projection of allProjections) {
209
+ if (!projection.canHandle.some((type) => eventTypes.includes(type))) continue;
210
+ await projection.handle(events, {
211
+ connection,
212
+ execute,
213
+ driverType
214
+ });
215
+ }
216
+ };
217
+ const sqliteProjection = (definition) => (0, _event_driven_io_emmett.projection)(definition);
218
+ const sqliteRawBatchSQLProjection = (options) => sqliteProjection({
219
+ name: options.name,
220
+ kind: options.kind ?? "emt:projections:sqlite:raw_sql:batch",
221
+ version: options.version,
222
+ canHandle: options.canHandle,
223
+ eventsOptions: options.eventsOptions,
224
+ handle: async (events, context) => {
225
+ const sqls = await options.evolve(events, context);
226
+ await context.execute.batchCommand(sqls);
227
+ },
228
+ init: async (initOptions) => {
229
+ const initSQL = options.init ? await options.init(initOptions) : void 0;
230
+ if (initSQL) if (Array.isArray(initSQL)) await initOptions.context.execute.batchCommand(initSQL);
231
+ else await initOptions.context.execute.command(initSQL);
232
+ }
233
+ });
234
+ const sqliteRawSQLProjection = (options) => {
235
+ const { evolve, kind, ...rest } = options;
236
+ return sqliteRawBatchSQLProjection({
237
+ kind: kind ?? "emt:projections:sqlite:raw:_sql:single",
238
+ ...rest,
239
+ evolve: async (events, context) => {
240
+ const sqls = [];
241
+ for (const event of events) {
242
+ const pendingSqls = await evolve(event, context);
243
+ if (Array.isArray(pendingSqls)) sqls.push(...pendingSqls);
244
+ else sqls.push(pendingSqls);
245
+ }
246
+ return sqls;
247
+ }
248
+ });
249
+ };
250
+
251
+ //#endregion
252
+ //#region src/eventStore/projections/sqliteProjectionSpec.ts
253
+ const SQLiteProjectionSpec = { for: (options) => {
254
+ {
255
+ const driverType = options.driver.driverType;
256
+ const pool = options.pool ?? (0, _event_driven_io_dumbo.dumbo)({
257
+ serialization: options.serialization,
258
+ transactionOptions: {
259
+ allowNestedTransactions: true,
260
+ mode: "session_based"
261
+ },
262
+ ...options.driver.mapToDumboOptions(options)
263
+ });
264
+ const projection = options.projection;
265
+ let wasInitialized = false;
266
+ return (givenEvents) => {
267
+ return { when: (events, options) => {
268
+ const allEvents = [];
269
+ const run = async (connection) => {
270
+ let globalPosition = 0n;
271
+ const numberOfTimes = options?.numberOfTimes ?? 1;
272
+ for (const event of [...givenEvents, ...Array.from({ length: numberOfTimes }).flatMap(() => events)]) {
273
+ const metadata = {
274
+ checkpoint: (0, _event_driven_io_emmett.bigIntProcessorCheckpoint)(++globalPosition),
275
+ globalPosition,
276
+ streamPosition: globalPosition,
277
+ streamName: `test-${(0, uuid.v4)()}`,
278
+ messageId: (0, uuid.v4)()
279
+ };
280
+ allEvents.push({
281
+ ...event,
282
+ kind: "Event",
283
+ metadata: {
284
+ ...metadata,
285
+ ..."metadata" in event ? event.metadata ?? {} : {}
286
+ }
287
+ });
288
+ }
289
+ if (!wasInitialized && projection.init) {
290
+ await projection.init({
291
+ registrationType: "async",
292
+ status: "active",
293
+ context: {
294
+ execute: connection.execute,
295
+ connection,
296
+ driverType
297
+ },
298
+ version: projection.version ?? 1
299
+ });
300
+ wasInitialized = true;
301
+ }
302
+ await connection.withTransaction(() => handleProjections({
303
+ events: allEvents,
304
+ projections: [projection],
305
+ execute: connection.execute,
306
+ connection,
307
+ driverType
308
+ }));
309
+ };
310
+ return {
311
+ then: (assert, message) => pool.withConnection(async (connection) => {
312
+ await run(connection);
313
+ const succeeded = await assert({ connection });
314
+ if (succeeded !== void 0 && succeeded === false) (0, _event_driven_io_emmett.assertFails)(message ?? "Projection specification didn't match the criteria");
315
+ }),
316
+ thenThrows: (...args) => pool.withConnection(async (connection) => {
317
+ try {
318
+ await run(connection);
319
+ throw new _event_driven_io_emmett.AssertionError("Handler did not fail as expected");
320
+ } catch (error) {
321
+ if (error instanceof _event_driven_io_emmett.AssertionError) throw error;
322
+ if (args.length === 0) return;
323
+ if (!(0, _event_driven_io_emmett.isErrorConstructor)(args[0])) {
324
+ (0, _event_driven_io_emmett.assertTrue)(args[0](error), `Error didn't match the error condition: ${error?.toString()}`);
325
+ return;
326
+ }
327
+ (0, _event_driven_io_emmett.assertTrue)(error instanceof args[0], `Caught error is not an instance of the expected type: ${error?.toString()}`);
328
+ if (args[1]) (0, _event_driven_io_emmett.assertTrue)(args[1](error), `Error didn't match the error condition: ${error?.toString()}`);
329
+ }
330
+ })
331
+ };
332
+ } };
333
+ };
334
+ }
335
+ } };
336
+ const eventInStream = (streamName, event) => {
337
+ return {
338
+ ...event,
339
+ metadata: {
340
+ ...event.metadata ?? {},
341
+ streamName: event.metadata?.streamName ?? streamName
342
+ }
343
+ };
344
+ };
345
+ const eventsInStream = (streamName, events) => {
346
+ return events.map((e) => eventInStream(streamName, e));
347
+ };
348
+ const newEventsInStream = eventsInStream;
349
+ const assertSQLQueryResultMatches = (sql, rows) => async ({ connection }) => {
350
+ const result = await connection.execute.query(sql);
351
+ (0, _event_driven_io_emmett.assertThatArray)(rows).containsExactlyInAnyOrder(result.rows);
352
+ };
353
+ const expectSQL = { query: (sql) => ({ resultRows: { toBeTheSame: (rows) => assertSQLQueryResultMatches(sql, rows) } }) };
354
+
355
+ //#endregion
356
+ //#region src/eventStore/schema/typing.ts
357
+ const emmettPrefix = "emt";
358
+ const globalTag = "global";
359
+ const defaultTag = `${"emt"}:default`;
360
+ const unknownTag = `${"emt"}:unknown`;
361
+ const globalNames = { module: `${"emt"}:module:${globalTag}` };
362
+ const columns = {
363
+ partition: { name: "partition" },
364
+ isArchived: { name: "is_archived" }
365
+ };
366
+ const streamsTable = {
367
+ name: `${"emt"}_streams`,
368
+ columns: {
369
+ partition: columns.partition,
370
+ isArchived: columns.isArchived
371
+ }
372
+ };
373
+ const messagesTable = {
374
+ name: `${"emt"}_messages`,
375
+ columns: {
376
+ partition: columns.partition,
377
+ isArchived: columns.isArchived
378
+ }
379
+ };
380
+ const processorsTable = { name: `${"emt"}_processors` };
381
+ const projectionsTable = { name: `${"emt"}_projections` };
382
+
383
+ //#endregion
384
+ //#region src/eventStore/schema/appendToStream.ts
385
+ const { identifier: identifier$7, merge } = _event_driven_io_dumbo.SQL;
386
+ const appendToStream = async (connection, streamName, streamType, messages, options) => {
387
+ if (messages.length === 0) return { success: false };
388
+ const expectedStreamVersion = toExpectedVersion(options?.expectedStreamVersion);
389
+ const messagesToAppend = messages.map((m, i) => ({
390
+ ...m,
391
+ kind: m.kind ?? "Event",
392
+ metadata: {
393
+ streamName,
394
+ messageId: (0, uuid.v4)(),
395
+ streamPosition: BigInt(i + 1),
396
+ ..."metadata" in m ? m.metadata ?? {} : {}
397
+ }
398
+ }));
399
+ try {
400
+ return await connection.withTransaction(async (transaction) => {
401
+ const result = await appendToStreamRaw(transaction.execute, streamName, streamType, (0, _event_driven_io_emmett.downcastRecordedMessages)(messagesToAppend, options?.schema?.versioning), { expectedStreamVersion });
402
+ if (options?.onBeforeCommit) await options.onBeforeCommit(messagesToAppend, { connection });
403
+ return {
404
+ success: true,
405
+ result
406
+ };
407
+ });
408
+ } catch (err) {
409
+ if ((0, _event_driven_io_emmett.isExpectedVersionConflictError)(err) || _event_driven_io_dumbo.DumboError.isInstanceOf(err, { errorType: _event_driven_io_dumbo.UniqueConstraintError.ErrorType }) || _event_driven_io_dumbo.DumboError.isInstanceOf(err, { errorType: _event_driven_io_dumbo.BatchCommandNoChangesError.ErrorType })) return { success: false };
410
+ throw err;
411
+ }
412
+ };
413
+ const toExpectedVersion = (expected) => {
414
+ if (expected === void 0) return null;
415
+ if (expected === _event_driven_io_emmett.NO_CONCURRENCY_CHECK) return null;
416
+ if (expected == _event_driven_io_emmett.STREAM_DOES_NOT_EXIST) return null;
417
+ if (expected == _event_driven_io_emmett.STREAM_EXISTS) return null;
418
+ return expected;
419
+ };
420
+ const appendToStreamRaw = async (execute, streamId, streamType, messages, options) => {
421
+ let expectedStreamVersion = options?.expectedStreamVersion ?? null;
422
+ const currentStreamVersion = await getLastStreamPosition(execute, streamId, expectedStreamVersion);
423
+ expectedStreamVersion ??= currentStreamVersion ?? 0n;
424
+ if (expectedStreamVersion !== currentStreamVersion) throw new _event_driven_io_emmett.ExpectedVersionConflictError(currentStreamVersion, expectedStreamVersion);
425
+ const streamSQL = expectedStreamVersion === 0n ? _event_driven_io_dumbo.SQL`INSERT INTO ${identifier$7(streamsTable.name)}
1645
426
  (stream_id, stream_position, partition, stream_type, stream_metadata, is_archived)
1646
427
  VALUES (
1647
428
  ${streamId},
1648
429
  ${messages.length},
1649
- ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _70 => _70.partition]), () => ( streamsTable.columns.partition))},
430
+ ${options?.partition ?? streamsTable.columns.partition},
1650
431
  ${streamType},
1651
432
  '[]',
1652
433
  false
1653
434
  )
1654
435
  RETURNING stream_position;
1655
- ` : _dumbo.SQL`UPDATE ${identifier(streamsTable.name)}
436
+ ` : _event_driven_io_dumbo.SQL`UPDATE ${identifier$7(streamsTable.name)}
1656
437
  SET stream_position = stream_position + ${messages.length}
1657
438
  WHERE stream_id = ${streamId}
1658
439
  AND stream_position = ${expectedStreamVersion}
1659
- AND partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _71 => _71.partition]), () => ( streamsTable.columns.partition))}
440
+ AND partition = ${options?.partition ?? streamsTable.columns.partition}
1660
441
  AND is_archived = false
1661
442
  RETURNING stream_position;
1662
443
  `;
1663
- const insertSQL = buildMessageInsertQuery(
1664
- messages,
1665
- expectedStreamVersion,
1666
- streamId,
1667
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _72 => _72.partition, 'optionalAccess', _73 => _73.toString, 'call', _74 => _74()]), () => ( defaultTag2))
1668
- );
1669
- const results = await execute.batchCommand([streamSQL, insertSQL], { assertChanges: true });
1670
- 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]);
1673
- if (!streamPosition)
1674
- throw new ExpectedVersionConflictError(0n, _nullishCoalesce(expectedStreamVersion, () => ( 0n)));
1675
- if (!globalPosition) throw new Error("Could not find global position");
1676
- return {
1677
- success: true,
1678
- nextStreamPosition: BigInt(streamPosition),
1679
- lastGlobalPosition: BigInt(globalPosition)
1680
- };
444
+ const insertSQL = buildMessageInsertQuery(messages, expectedStreamVersion, streamId, options?.partition?.toString() ?? defaultTag);
445
+ const [streamResult, messagesResult] = await execute.batchCommand([streamSQL, insertSQL], { assertChanges: true });
446
+ const streamPosition = streamResult?.rows[0]?.stream_position;
447
+ const globalPosition = messagesResult?.rows.at(-1)?.global_position;
448
+ if (!streamPosition) throw new _event_driven_io_emmett.ExpectedVersionConflictError(0n, expectedStreamVersion ?? 0n);
449
+ if (!globalPosition) throw new Error("Could not find global position");
450
+ return {
451
+ success: true,
452
+ nextStreamPosition: BigInt(streamPosition),
453
+ lastGlobalPosition: BigInt(globalPosition)
454
+ };
1681
455
  };
1682
456
  async function getLastStreamPosition(execute, streamId, expectedStreamVersion) {
1683
- const result = await _dumbo.singleOrNull.call(void 0,
1684
- execute.query(
1685
- _dumbo.SQL`SELECT CAST(stream_position AS VARCHAR) AS stream_position FROM ${identifier(streamsTable.name)} WHERE stream_id = ${streamId}`
1686
- )
1687
- );
1688
- if (_optionalChain([result, 'optionalAccess', _82 => _82.stream_position]) == null) {
1689
- expectedStreamVersion = 0n;
1690
- } else {
1691
- expectedStreamVersion = BigInt(result.stream_position);
1692
- }
1693
- return expectedStreamVersion;
457
+ const result = await (0, _event_driven_io_dumbo.singleOrNull)(execute.query(_event_driven_io_dumbo.SQL`SELECT CAST(stream_position AS VARCHAR) AS stream_position FROM ${identifier$7(streamsTable.name)} WHERE stream_id = ${streamId}`));
458
+ if (result?.stream_position == null) expectedStreamVersion = 0n;
459
+ else expectedStreamVersion = BigInt(result.stream_position);
460
+ return expectedStreamVersion;
1694
461
  }
1695
- var buildMessageInsertQuery = (messages, expectedStreamVersion, streamId, partition) => {
1696
- const values = messages.map((message) => {
1697
- if (_optionalChain([message, 'access', _83 => _83.metadata, 'optionalAccess', _84 => _84.streamPosition]) == null || typeof message.metadata.streamPosition !== "bigint") {
1698
- throw new Error("Stream position is required");
1699
- }
1700
- const streamPosition = BigInt(message.metadata.streamPosition) + BigInt(expectedStreamVersion);
1701
- return _dumbo.SQL`(${streamId},${_nullishCoalesce(streamPosition, () => ( 0n))},${_nullishCoalesce(partition, () => ( defaultTag2))},${message.kind === "Event" ? "E" : "C"},${message.data},${message.metadata},${_nullishCoalesce(expectedStreamVersion, () => ( 0n))},${message.type},${message.metadata.messageId},${false})`;
1702
- });
1703
- return _dumbo.SQL`
1704
- INSERT INTO ${identifier(messagesTable.name)} (
462
+ const buildMessageInsertQuery = (messages, expectedStreamVersion, streamId, partition) => {
463
+ const values = messages.map((message) => {
464
+ if (message.metadata?.streamPosition == null || typeof message.metadata.streamPosition !== "bigint") throw new Error("Stream position is required");
465
+ return _event_driven_io_dumbo.SQL`(${streamId},${BigInt(message.metadata.streamPosition) + BigInt(expectedStreamVersion) ?? 0n},${partition ?? defaultTag},${message.kind === "Event" ? "E" : "C"},${message.data},${message.metadata},${expectedStreamVersion ?? 0n},${message.type},${message.metadata.messageId},${false})`;
466
+ });
467
+ return _event_driven_io_dumbo.SQL`
468
+ INSERT INTO ${identifier$7(messagesTable.name)} (
1705
469
  stream_id,
1706
470
  stream_position,
1707
471
  partition,
@@ -1719,10 +483,10 @@ var buildMessageInsertQuery = (messages, expectedStreamVersion, streamId, partit
1719
483
  `;
1720
484
  };
1721
485
 
1722
- // src/eventStore/schema/migrations/0_41_0/0_41_0.snapshot.ts
1723
-
1724
- var schema_0_41_0 = [
1725
- _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_streams(
486
+ //#endregion
487
+ //#region src/eventStore/schema/migrations/0_41_0/0_41_0.snapshot.ts
488
+ const schema_0_41_0 = [
489
+ _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_streams(
1726
490
  stream_id TEXT NOT NULL,
1727
491
  stream_position BIGINT NOT NULL DEFAULT 0,
1728
492
  partition TEXT NOT NULL DEFAULT 'global',
@@ -1732,7 +496,7 @@ var schema_0_41_0 = [
1732
496
  PRIMARY KEY (stream_id, partition, is_archived),
1733
497
  UNIQUE (stream_id, partition, is_archived)
1734
498
  )`,
1735
- _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_messages(
499
+ _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_messages(
1736
500
  stream_id TEXT NOT NULL,
1737
501
  stream_position BIGINT NOT NULL,
1738
502
  partition TEXT NOT NULL DEFAULT 'global',
@@ -1747,7 +511,7 @@ var schema_0_41_0 = [
1747
511
  created DATETIME DEFAULT CURRENT_TIMESTAMP,
1748
512
  UNIQUE (stream_id, stream_position, partition, is_archived)
1749
513
  )`,
1750
- _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_subscriptions(
514
+ _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_subscriptions(
1751
515
  subscription_id TEXT NOT NULL,
1752
516
  version INTEGER NOT NULL DEFAULT 1,
1753
517
  partition TEXT NOT NULL DEFAULT 'global',
@@ -1756,30 +520,30 @@ var schema_0_41_0 = [
1756
520
  )`
1757
521
  ];
1758
522
 
1759
- // src/eventStore/schema/migrations/0_42_0/0_42_0.migration.ts
1760
-
1761
- var { identifier: identifier2, plain } = _dumbo.SQL;
1762
- var migration_0_42_0_SQLs = [
1763
- _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier2(processorsTable.name)}(
523
+ //#endregion
524
+ //#region src/eventStore/schema/migrations/0_42_0/0_42_0.migration.ts
525
+ const { identifier: identifier$6, plain: plain$1 } = _event_driven_io_dumbo.SQL;
526
+ const migration_0_42_0_SQLs = [
527
+ _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier$6(processorsTable.name)}(
1764
528
  processor_id TEXT NOT NULL,
1765
529
  version INTEGER NOT NULL DEFAULT 1,
1766
- partition TEXT NOT NULL DEFAULT '${plain(globalTag)}',
530
+ partition TEXT NOT NULL DEFAULT '${plain$1(globalTag)}',
1767
531
  status TEXT NOT NULL DEFAULT 'stopped',
1768
532
  last_processed_checkpoint TEXT NOT NULL,
1769
533
  processor_instance_id TEXT DEFAULT 'emt:unknown',
1770
534
  PRIMARY KEY (processor_id, partition, version)
1771
535
  )`,
1772
- _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier2(projectionsTable.name)}(
536
+ _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier$6(projectionsTable.name)}(
1773
537
  name TEXT NOT NULL,
1774
538
  version INTEGER NOT NULL DEFAULT 1,
1775
- partition TEXT NOT NULL DEFAULT '${plain(globalTag)}',
539
+ partition TEXT NOT NULL DEFAULT '${plain$1(globalTag)}',
1776
540
  type CHAR(1) NOT NULL,
1777
541
  kind TEXT NOT NULL,
1778
542
  status TEXT NOT NULL,
1779
543
  definition JSONB NOT NULL DEFAULT '{}',
1780
544
  PRIMARY KEY (name, partition, version)
1781
545
  )`,
1782
- _dumbo.SQL`INSERT INTO ${identifier2(processorsTable.name)}
546
+ _event_driven_io_dumbo.SQL`INSERT INTO ${identifier$6(processorsTable.name)}
1783
547
  (processor_id, version, partition, status, last_processed_checkpoint, processor_instance_id)
1784
548
  SELECT
1785
549
  subscription_id,
@@ -1789,24 +553,17 @@ var migration_0_42_0_SQLs = [
1789
553
  printf('%019d', last_processed_position),
1790
554
  'emt:unknown'
1791
555
  FROM emt_subscriptions`,
1792
- _dumbo.SQL`DROP TABLE emt_subscriptions`
556
+ _event_driven_io_dumbo.SQL`DROP TABLE emt_subscriptions`
1793
557
  ];
1794
- var migration_0_42_0_FromSubscriptionsToProcessors = async (execute) => {
1795
- const tableExists = await _dumbo.singleOrNull.call(void 0,
1796
- execute.query(
1797
- _dumbo.SQL`SELECT name FROM sqlite_master WHERE type='table' AND name='emt_subscriptions'`
1798
- )
1799
- );
1800
- if (!tableExists) {
1801
- return;
1802
- }
1803
- await execute.batchCommand(migration_0_42_0_SQLs);
558
+ const migration_0_42_0_FromSubscriptionsToProcessors = async (execute) => {
559
+ if (!await (0, _event_driven_io_dumbo.singleOrNull)(execute.query(_event_driven_io_dumbo.SQL`SELECT name FROM sqlite_master WHERE type='table' AND name='emt_subscriptions'`))) return;
560
+ await execute.batchCommand(migration_0_42_0_SQLs);
1804
561
  };
1805
562
 
1806
- // src/eventStore/schema/migrations/0_42_0/0_42_0.snapshot.ts
1807
-
1808
- var schema_0_42_0 = [
1809
- _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_streams(
563
+ //#endregion
564
+ //#region src/eventStore/schema/migrations/0_42_0/0_42_0.snapshot.ts
565
+ const schema_0_42_0 = [
566
+ _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_streams(
1810
567
  stream_id TEXT NOT NULL,
1811
568
  stream_position BIGINT NOT NULL DEFAULT 0,
1812
569
  partition TEXT NOT NULL DEFAULT 'global',
@@ -1816,7 +573,7 @@ var schema_0_42_0 = [
1816
573
  PRIMARY KEY (stream_id, partition, is_archived),
1817
574
  UNIQUE (stream_id, partition, is_archived)
1818
575
  )`,
1819
- _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_messages(
576
+ _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_messages(
1820
577
  stream_id TEXT NOT NULL,
1821
578
  stream_position BIGINT NOT NULL,
1822
579
  partition TEXT NOT NULL DEFAULT 'global',
@@ -1831,7 +588,7 @@ var schema_0_42_0 = [
1831
588
  created DATETIME DEFAULT CURRENT_TIMESTAMP,
1832
589
  UNIQUE (stream_id, stream_position, partition, is_archived)
1833
590
  )`,
1834
- _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_processors(
591
+ _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_processors(
1835
592
  processor_id TEXT NOT NULL,
1836
593
  version INTEGER NOT NULL DEFAULT 1,
1837
594
  partition TEXT NOT NULL DEFAULT 'global',
@@ -1840,7 +597,7 @@ var schema_0_42_0 = [
1840
597
  processor_instance_id TEXT DEFAULT 'emt:unknown',
1841
598
  PRIMARY KEY (processor_id, partition, version)
1842
599
  )`,
1843
- _dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_projections(
600
+ _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS emt_projections(
1844
601
  name TEXT NOT NULL,
1845
602
  version INTEGER NOT NULL DEFAULT 1,
1846
603
  partition TEXT NOT NULL DEFAULT 'global',
@@ -1852,801 +609,657 @@ var schema_0_42_0 = [
1852
609
  )`
1853
610
  ];
1854
611
 
1855
- // src/eventStore/schema/readLastMessageGlobalPosition.ts
1856
-
1857
- var { identifier: identifier3 } = _dumbo.SQL;
1858
- var readLastMessageGlobalPosition = async (execute, options) => {
1859
- const result = await _dumbo.singleOrNull.call(void 0,
1860
- execute.query(
1861
- _dumbo.SQL`
612
+ //#endregion
613
+ //#region src/eventStore/schema/readLastMessageGlobalPosition.ts
614
+ const { identifier: identifier$5 } = _event_driven_io_dumbo.SQL;
615
+ const readLastMessageGlobalPosition = async (execute, options) => {
616
+ const result = await (0, _event_driven_io_dumbo.singleOrNull)(execute.query(_event_driven_io_dumbo.SQL`
1862
617
  SELECT global_position
1863
- FROM ${identifier3(messagesTable.name)}
1864
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _85 => _85.partition]), () => ( defaultTag2))} AND is_archived = FALSE
1865
- ORDER BY global_position
1866
- LIMIT 1`
1867
- )
1868
- );
1869
- return {
1870
- currentGlobalPosition: result !== null ? BigInt(result.global_position) : null
1871
- };
1872
- };
1873
-
1874
- // src/eventStore/schema/readMessagesBatch.ts
1875
-
1876
- var { identifier: identifier4 } = _dumbo.SQL;
1877
- var readMessagesBatch = async (execute, options) => {
1878
- const { serializer } = options;
1879
- const from = "from" in options ? options.from : void 0;
1880
- const after = "after" in options ? options.after : void 0;
1881
- const batchSize = "batchSize" in options ? options.batchSize : options.to - options.from;
1882
- const fromCondition = from !== void 0 ? _dumbo.SQL`AND global_position >= ${from}` : after !== void 0 ? _dumbo.SQL`AND global_position > ${after}` : _dumbo.SQL.EMPTY;
1883
- const toCondition = "to" in options ? _dumbo.SQL`AND global_position <= ${options.to}` : _dumbo.SQL.EMPTY;
1884
- const limitCondition = "batchSize" in options ? _dumbo.SQL`LIMIT ${options.batchSize}` : _dumbo.SQL.EMPTY;
1885
- const messages = await _dumbo.mapRows.call(void 0,
1886
- execute.query(
1887
- _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
1888
- FROM ${identifier4(messagesTable.name)}
1889
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _86 => _86.partition]), () => ( defaultTag2))} AND is_archived = FALSE ${fromCondition} ${toCondition}
618
+ FROM ${identifier$5(messagesTable.name)}
619
+ WHERE partition = ${options?.partition ?? defaultTag} AND is_archived = FALSE
620
+ ORDER BY global_position DESC
621
+ LIMIT 1`));
622
+ return { currentGlobalPosition: result !== null ? BigInt(result.global_position) : null };
623
+ };
624
+
625
+ //#endregion
626
+ //#region src/eventStore/schema/readMessagesBatch.ts
627
+ const { identifier: identifier$4 } = _event_driven_io_dumbo.SQL;
628
+ const readMessagesBatch = async (execute, options) => {
629
+ const { serializer } = options;
630
+ const from = "from" in options ? options.from : void 0;
631
+ const after = "after" in options ? options.after : void 0;
632
+ const batchSize = "batchSize" in options ? options.batchSize : options.to - options.from;
633
+ const fromCondition = from !== void 0 ? _event_driven_io_dumbo.SQL`AND global_position >= ${from}` : after !== void 0 ? _event_driven_io_dumbo.SQL`AND global_position > ${after}` : _event_driven_io_dumbo.SQL.EMPTY;
634
+ const toCondition = "to" in options ? _event_driven_io_dumbo.SQL`AND global_position <= ${options.to}` : _event_driven_io_dumbo.SQL.EMPTY;
635
+ const limitCondition = "batchSize" in options ? _event_driven_io_dumbo.SQL`LIMIT ${options.batchSize}` : _event_driven_io_dumbo.SQL.EMPTY;
636
+ const messages = await (0, _event_driven_io_dumbo.mapRows)(execute.query(_event_driven_io_dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
637
+ FROM ${identifier$4(messagesTable.name)}
638
+ WHERE partition = ${options?.partition ?? defaultTag} AND is_archived = FALSE ${fromCondition} ${toCondition}
1890
639
  ORDER BY global_position
1891
- ${limitCondition}`
1892
- ),
1893
- (row) => {
1894
- const rawEvent = {
1895
- type: row.message_type,
1896
- data: serializer.deserialize(row.message_data),
1897
- metadata: serializer.deserialize(row.message_metadata)
1898
- };
1899
- const metadata = {
1900
- ..."metadata" in rawEvent ? _nullishCoalesce(rawEvent.metadata, () => ( {})) : {},
1901
- messageId: row.message_id,
1902
- streamName: row.stream_id,
1903
- streamPosition: BigInt(row.stream_position),
1904
- globalPosition: BigInt(row.global_position),
1905
- checkpoint: bigIntProcessorCheckpoint(BigInt(row.global_position))
1906
- };
1907
- return {
1908
- ...rawEvent,
1909
- kind: "Event",
1910
- metadata
1911
- };
1912
- }
1913
- );
1914
- return messages.length > 0 ? {
1915
- currentGlobalPosition: messages[messages.length - 1].metadata.globalPosition,
1916
- messages,
1917
- areMessagesLeft: messages.length === batchSize
1918
- } : {
1919
- currentGlobalPosition: "from" in options ? options.from : "after" in options ? options.after : 0n,
1920
- messages: [],
1921
- areMessagesLeft: false
1922
- };
1923
- };
1924
-
1925
- // src/eventStore/schema/readProcessorCheckpoint.ts
1926
-
1927
- var { identifier: identifier5 } = _dumbo.SQL;
1928
- var readProcessorCheckpoint = async (execute, options) => {
1929
- const result = await _dumbo.singleOrNull.call(void 0,
1930
- execute.query(
1931
- _dumbo.SQL`SELECT last_processed_checkpoint
1932
- FROM ${identifier5(processorsTable.name)}
1933
- WHERE partition = ${_nullishCoalesce(_optionalChain([options, 'optionalAccess', _87 => _87.partition]), () => ( defaultTag2))} AND processor_id = ${options.processorId}
1934
- LIMIT 1`
1935
- )
1936
- );
1937
- return {
1938
- lastProcessedCheckpoint: result !== null ? result.last_processed_checkpoint : null
1939
- };
1940
- };
1941
-
1942
- // src/eventStore/schema/readStream.ts
1943
-
1944
-
1945
- // src/eventStore/SQLiteEventStore.ts
1946
-
1947
-
1948
- // src/eventStore/consumers/messageBatchProcessing/index.ts
1949
- var DefaultSQLiteEventStoreProcessorBatchSize = 100;
1950
- var DefaultSQLiteEventStoreProcessorPullingFrequencyInMs = 50;
1951
- var sqliteEventStoreMessageBatchPuller = ({
1952
- executor,
1953
- batchSize,
1954
- eachBatch,
1955
- pullingFrequencyInMs,
1956
- stopWhen,
1957
- signal,
1958
- serialization
1959
- }) => {
1960
- let isRunning = false;
1961
- let start;
1962
- const serializer = JSONSerializer.from({ serialization });
1963
- const pullMessages = async (options) => {
1964
- const after = options.startFrom === "BEGINNING" ? 0n : options.startFrom === "END" ? await _asyncNullishCoalesce((await readLastMessageGlobalPosition(executor)).currentGlobalPosition, async () => ( 0n)) : parseBigIntProcessorCheckpoint(options.startFrom.lastCheckpoint);
1965
- const readMessagesOptions = {
1966
- after,
1967
- batchSize,
1968
- serializer
1969
- };
1970
- let waitTime = 100;
1971
- while (isRunning && !_optionalChain([signal, 'optionalAccess', _88 => _88.aborted])) {
1972
- const { messages, currentGlobalPosition, areMessagesLeft } = await readMessagesBatch(executor, readMessagesOptions);
1973
- if (messages.length > 0) {
1974
- const result = await eachBatch(messages);
1975
- if (result && result.type === "STOP") {
1976
- isRunning = false;
1977
- break;
1978
- }
1979
- }
1980
- readMessagesOptions.after = currentGlobalPosition;
1981
- await new Promise((resolve) => setTimeout(resolve, waitTime));
1982
- if (_optionalChain([stopWhen, 'optionalAccess', _89 => _89.noMessagesLeft]) === true && !areMessagesLeft) {
1983
- isRunning = false;
1984
- break;
1985
- }
1986
- if (!areMessagesLeft) {
1987
- waitTime = Math.min(waitTime * 2, 1e3);
1988
- } else {
1989
- waitTime = pullingFrequencyInMs;
1990
- }
1991
- }
1992
- };
1993
- return {
1994
- get isRunning() {
1995
- return isRunning;
1996
- },
1997
- start: (options) => {
1998
- if (isRunning) return start;
1999
- isRunning = true;
2000
- start = (async () => {
2001
- return pullMessages(options);
2002
- })();
2003
- return start;
2004
- },
2005
- stop: async () => {
2006
- if (!isRunning) return;
2007
- isRunning = false;
2008
- await start;
2009
- }
2010
- };
2011
- };
2012
- var zipSQLiteEventStoreMessageBatchPullerStartFrom = (options) => {
2013
- if (options.length === 0 || options.some((o) => o === void 0 || o === "BEGINNING"))
2014
- return "BEGINNING";
2015
- if (options.every((o) => o === "END")) return "END";
2016
- return options.filter((o) => o !== void 0 && o !== "BEGINNING" && o !== "END").sort((a, b) => a > b ? 1 : -1)[0];
2017
- };
2018
-
2019
- // src/eventStore/consumers/sqliteEventStoreConsumer.ts
2020
-
2021
-
2022
-
2023
- // src/eventStore/consumers/sqliteCheckpointer.ts
2024
- var sqliteCheckpointer = () => ({
2025
- read: async (options, context) => {
2026
- const result = await readProcessorCheckpoint(context.execute, options);
2027
- return { lastCheckpoint: _optionalChain([result, 'optionalAccess', _90 => _90.lastProcessedCheckpoint]) };
2028
- },
2029
- store: async (options, context) => {
2030
- const newCheckpoint = getCheckpoint(options.message);
2031
- const result = await storeProcessorCheckpoint(context.execute, {
2032
- lastProcessedCheckpoint: options.lastCheckpoint,
2033
- newCheckpoint,
2034
- processorId: options.processorId,
2035
- partition: options.partition,
2036
- version: options.version
2037
- });
2038
- return result.success ? { success: true, newCheckpoint: result.newCheckpoint } : result;
2039
- }
640
+ ${limitCondition}`), (row) => {
641
+ const rawEvent = {
642
+ type: row.message_type,
643
+ data: serializer.deserialize(row.message_data),
644
+ metadata: serializer.deserialize(row.message_metadata)
645
+ };
646
+ const metadata = {
647
+ ..."metadata" in rawEvent ? rawEvent.metadata ?? {} : {},
648
+ messageId: row.message_id,
649
+ streamName: row.stream_id,
650
+ streamPosition: BigInt(row.stream_position),
651
+ globalPosition: BigInt(row.global_position),
652
+ checkpoint: (0, _event_driven_io_emmett.bigIntProcessorCheckpoint)(BigInt(row.global_position))
653
+ };
654
+ return {
655
+ ...rawEvent,
656
+ kind: "Event",
657
+ metadata
658
+ };
659
+ });
660
+ return messages.length > 0 ? {
661
+ currentGlobalPosition: messages[messages.length - 1].metadata.globalPosition,
662
+ messages,
663
+ areMessagesLeft: messages.length === batchSize
664
+ } : {
665
+ currentGlobalPosition: "from" in options ? options.from : "after" in options ? options.after : 0n,
666
+ messages: [],
667
+ areMessagesLeft: false
668
+ };
669
+ };
670
+
671
+ //#endregion
672
+ //#region src/eventStore/schema/readProcessorCheckpoint.ts
673
+ const { identifier: identifier$3 } = _event_driven_io_dumbo.SQL;
674
+ const readProcessorCheckpoint = async (execute, options) => {
675
+ const result = await (0, _event_driven_io_dumbo.singleOrNull)(execute.query(_event_driven_io_dumbo.SQL`SELECT last_processed_checkpoint
676
+ FROM ${identifier$3(processorsTable.name)}
677
+ WHERE partition = ${options?.partition ?? defaultTag} AND processor_id = ${options.processorId}
678
+ LIMIT 1`));
679
+ return { lastProcessedCheckpoint: result !== null ? result.last_processed_checkpoint : null };
680
+ };
681
+
682
+ //#endregion
683
+ //#region src/eventStore/consumers/messageBatchProcessing/index.ts
684
+ const sqliteEventStoreMessageBatchPuller = ({ executor, batchSize, eachBatch, pullingFrequencyInMs, stopWhen, signal, serialization }) => {
685
+ let isRunning = false;
686
+ let start;
687
+ const serializer = _event_driven_io_emmett.JSONSerializer.from({ serialization });
688
+ const pullMessages = async (options) => {
689
+ let after;
690
+ try {
691
+ after = options.startFrom === "BEGINNING" ? 0n : options.startFrom === "END" ? (await readLastMessageGlobalPosition(executor)).currentGlobalPosition ?? 0n : (0, _event_driven_io_emmett.parseBigIntProcessorCheckpoint)(options.startFrom.lastCheckpoint);
692
+ } catch (error) {
693
+ options.started?.reject(error);
694
+ throw error;
695
+ }
696
+ options.started?.resolve();
697
+ const readMessagesOptions = {
698
+ after,
699
+ batchSize,
700
+ serializer
701
+ };
702
+ let waitTime = 100;
703
+ while (isRunning && !signal?.aborted) {
704
+ const { messages, currentGlobalPosition, areMessagesLeft } = await readMessagesBatch(executor, readMessagesOptions);
705
+ if (messages.length > 0) {
706
+ const result = await eachBatch(messages);
707
+ if (result && result.type === "STOP") {
708
+ isRunning = false;
709
+ break;
710
+ }
711
+ }
712
+ readMessagesOptions.after = currentGlobalPosition;
713
+ await new Promise((resolve) => setTimeout(resolve, waitTime));
714
+ if (stopWhen?.noMessagesLeft === true && !areMessagesLeft) {
715
+ isRunning = false;
716
+ break;
717
+ }
718
+ if (!areMessagesLeft) waitTime = Math.min(waitTime * 2, 1e3);
719
+ else waitTime = pullingFrequencyInMs;
720
+ }
721
+ };
722
+ return {
723
+ get isRunning() {
724
+ return isRunning;
725
+ },
726
+ start: (options) => {
727
+ if (isRunning) return start;
728
+ isRunning = true;
729
+ start = (async () => {
730
+ return pullMessages(options);
731
+ })();
732
+ return start;
733
+ },
734
+ stop: async () => {
735
+ if (!isRunning) return;
736
+ isRunning = false;
737
+ await start;
738
+ }
739
+ };
740
+ };
741
+ const zipSQLiteEventStoreMessageBatchPullerStartFrom = (options) => {
742
+ if (options.length === 0 || options.some((o) => o === void 0 || o === "BEGINNING")) return "BEGINNING";
743
+ if (options.every((o) => o === "END")) return "END";
744
+ return options.filter((o) => o !== void 0 && o !== "BEGINNING" && o !== "END").sort((a, b) => a > b ? 1 : -1)[0];
745
+ };
746
+
747
+ //#endregion
748
+ //#region src/eventStore/consumers/sqliteCheckpointer.ts
749
+ const sqliteCheckpointer = () => ({
750
+ read: async (options, context) => {
751
+ return { lastCheckpoint: (await readProcessorCheckpoint(context.execute, options))?.lastProcessedCheckpoint };
752
+ },
753
+ store: async (options, context) => {
754
+ const newCheckpoint = (0, _event_driven_io_emmett.getCheckpoint)(options.message);
755
+ const result = await storeProcessorCheckpoint(context.execute, {
756
+ lastProcessedCheckpoint: options.lastCheckpoint,
757
+ newCheckpoint,
758
+ processorId: options.processorId,
759
+ partition: options.partition,
760
+ version: options.version
761
+ });
762
+ return result.success ? {
763
+ success: true,
764
+ newCheckpoint: result.newCheckpoint
765
+ } : result;
766
+ }
2040
767
  });
2041
768
 
2042
- // src/eventStore/consumers/sqliteProcessor.ts
2043
- var sqliteProcessingScope = () => {
2044
- const processingScope = async (handler, partialContext) => {
2045
- const connection = _optionalChain([partialContext, 'optionalAccess', _91 => _91.connection]);
2046
- if (!connection)
2047
- throw new EmmettError("Connection is required in context or options");
2048
- return connection.withTransaction(
2049
- async (transaction) => {
2050
- return handler({
2051
- ...partialContext,
2052
- connection,
2053
- execute: transaction.execute
2054
- });
2055
- }
2056
- );
2057
- };
2058
- return processingScope;
2059
- };
2060
- var sqliteWorkflowProcessingScope = (messageStore) => {
2061
- const processingScope = async (handler, partialContext) => {
2062
- const connection = _optionalChain([partialContext, 'optionalAccess', _92 => _92.connection]);
2063
- if (!connection)
2064
- throw new EmmettError("Connection is required in context or options");
2065
- return connection.withTransaction(
2066
- async (transaction) => {
2067
- return handler({
2068
- ...partialContext,
2069
- connection: Object.assign(connection, { messageStore }),
2070
- execute: transaction.execute
2071
- });
2072
- }
2073
- );
2074
- };
2075
- return processingScope;
2076
- };
2077
- var sqliteWorkflowProcessor = (options) => {
2078
- const {
2079
- processorId = _nullishCoalesce(options.processorId, () => ( getWorkflowId({
2080
- workflowName: _nullishCoalesce(options.workflow.name, () => ( "unknown"))
2081
- }))),
2082
- processorInstanceId = getProcessorInstanceId(processorId),
2083
- version = defaultProcessorVersion,
2084
- partition = defaultProcessorPartition
2085
- } = options;
2086
- const hooks = {
2087
- ..._nullishCoalesce(options.hooks, () => ( {})),
2088
- onClose: _optionalChain([options, 'access', _93 => _93.hooks, 'optionalAccess', _94 => _94.onClose])
2089
- };
2090
- return workflowProcessor({
2091
- ...options,
2092
- processorId,
2093
- processorInstanceId,
2094
- version,
2095
- partition,
2096
- hooks,
2097
- processingScope: sqliteWorkflowProcessingScope(
2098
- options.messageStore
2099
- ),
2100
- checkpoints: sqliteCheckpointer()
2101
- });
2102
- };
2103
- var sqliteReactor = (options) => {
2104
- const {
2105
- processorId = options.processorId,
2106
- processorInstanceId = getProcessorInstanceId(processorId),
2107
- version = defaultProcessorVersion,
2108
- partition = defaultProcessorPartition,
2109
- hooks
2110
- } = options;
2111
- return reactor({
2112
- ...options,
2113
- processorId,
2114
- processorInstanceId,
2115
- version,
2116
- partition,
2117
- hooks,
2118
- processingScope: sqliteProcessingScope(),
2119
- checkpoints: sqliteCheckpointer()
2120
- });
2121
- };
2122
- var sqliteProjector = (options) => {
2123
- const {
2124
- processorId = getProjectorId({
2125
- projectionName: _nullishCoalesce(options.projection.name, () => ( "unknown"))
2126
- }),
2127
- processorInstanceId = getProcessorInstanceId(processorId),
2128
- version = defaultProcessorVersion,
2129
- partition = defaultProcessorPartition
2130
- } = options;
2131
- const hooks = {
2132
- ..._nullishCoalesce(options.hooks, () => ( {})),
2133
- onInit: options.projection.init !== void 0 || _optionalChain([options, 'access', _95 => _95.hooks, 'optionalAccess', _96 => _96.onInit]) ? async (context) => {
2134
- if (options.projection.init)
2135
- await options.projection.init({
2136
- version: _nullishCoalesce(options.projection.version, () => ( version)),
2137
- status: "active",
2138
- registrationType: "async",
2139
- context: {
2140
- ...context,
2141
- migrationOptions: options.migrationOptions
2142
- }
2143
- });
2144
- if (_optionalChain([options, 'access', _97 => _97.hooks, 'optionalAccess', _98 => _98.onInit]))
2145
- await options.hooks.onInit({
2146
- ...context,
2147
- migrationOptions: options.migrationOptions
2148
- });
2149
- } : _optionalChain([options, 'access', _99 => _99.hooks, 'optionalAccess', _100 => _100.onInit]),
2150
- onClose: _optionalChain([options, 'access', _101 => _101.hooks, 'optionalAccess', _102 => _102.onClose])
2151
- };
2152
- const processor = projector({
2153
- ...options,
2154
- processorId,
2155
- processorInstanceId,
2156
- version,
2157
- partition,
2158
- hooks,
2159
- processingScope: sqliteProcessingScope(),
2160
- checkpoints: sqliteCheckpointer()
2161
- });
2162
- return processor;
2163
- };
2164
-
2165
- // src/eventStore/consumers/sqliteEventStoreConsumer.ts
2166
- var sqliteEventStoreConsumer = (options) => {
2167
- let isRunning = false;
2168
- let isInitialized = false;
2169
- const { pulling } = options;
2170
- const processors = _nullishCoalesce(options.processors, () => ( []));
2171
- let abortController = null;
2172
- let start;
2173
- let messagePuller;
2174
- const pool = _nullishCoalesce(options.pool, () => ( _dumbo.dumbo.call(void 0, {
2175
- serialization: options.serialization,
2176
- transactionOptions: {
2177
- allowNestedTransactions: true,
2178
- mode: "session_based"
2179
- },
2180
- ...options.driver.mapToDumboOptions(options)
2181
- })));
2182
- const eachBatch = (messagesBatch) => pool.withConnection(async (connection) => {
2183
- const activeProcessors = processors.filter((s) => s.isActive);
2184
- if (activeProcessors.length === 0)
2185
- return {
2186
- type: "STOP",
2187
- reason: "No active processors"
2188
- };
2189
- const result = await Promise.allSettled(
2190
- activeProcessors.map(async (s) => {
2191
- return await s.handle(messagesBatch, {
2192
- connection,
2193
- execute: connection.execute
2194
- });
2195
- })
2196
- );
2197
- return result.some(
2198
- (r) => r.status === "fulfilled" && _optionalChain([r, 'access', _103 => _103.value, 'optionalAccess', _104 => _104.type]) !== "STOP"
2199
- ) ? void 0 : {
2200
- type: "STOP"
2201
- };
2202
- });
2203
- const processorContext = {
2204
- execute: void 0,
2205
- connection: void 0
2206
- };
2207
- const stopProcessors = () => Promise.all(processors.map((p) => p.close(processorContext)));
2208
- const stop = async () => {
2209
- if (!isRunning) return;
2210
- isRunning = false;
2211
- if (messagePuller) {
2212
- _optionalChain([abortController, 'optionalAccess', _105 => _105.abort, 'call', _106 => _106()]);
2213
- await messagePuller.stop();
2214
- }
2215
- await start;
2216
- messagePuller = void 0;
2217
- abortController = null;
2218
- await stopProcessors();
2219
- };
2220
- const init = async () => {
2221
- if (isInitialized) return;
2222
- const sqliteProcessors = processors;
2223
- await pool.withConnection(async (connection) => {
2224
- for (const processor of sqliteProcessors) {
2225
- if (processor.init) {
2226
- await processor.init({
2227
- ...processorContext,
2228
- connection,
2229
- execute: connection.execute
2230
- });
2231
- }
2232
- }
2233
- });
2234
- isInitialized = true;
2235
- };
2236
- return {
2237
- consumerId: _nullishCoalesce(options.consumerId, () => ( _uuid.v7.call(void 0, ))),
2238
- get isRunning() {
2239
- return isRunning;
2240
- },
2241
- processors,
2242
- init,
2243
- reactor: (options2) => {
2244
- const processor = sqliteReactor(options2);
2245
- processors.push(
2246
- // TODO: change that
2247
- processor
2248
- );
2249
- return processor;
2250
- },
2251
- projector: (options2) => {
2252
- const processor = sqliteProjector(options2);
2253
- processors.push(
2254
- // TODO: change that
2255
- processor
2256
- );
2257
- return processor;
2258
- },
2259
- workflowProcessor: (processorOptions) => {
2260
- const messageStore = getSQLiteEventStore({
2261
- ...options,
2262
- pool,
2263
- schema: { autoMigration: "None" }
2264
- });
2265
- const processor = sqliteWorkflowProcessor({
2266
- ...processorOptions,
2267
- messageStore
2268
- });
2269
- processors.push(
2270
- // TODO: change that
2271
- processor
2272
- );
2273
- return processor;
2274
- },
2275
- start: () => {
2276
- if (isRunning) return start;
2277
- if (processors.length === 0)
2278
- throw new EmmettError(
2279
- "Cannot start consumer without at least a single processor"
2280
- );
2281
- isRunning = true;
2282
- abortController = new AbortController();
2283
- messagePuller = sqliteEventStoreMessageBatchPuller({
2284
- stopWhen: options.stopWhen,
2285
- executor: pool.execute,
2286
- eachBatch,
2287
- batchSize: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _107 => _107.batchSize]), () => ( DefaultSQLiteEventStoreProcessorBatchSize)),
2288
- pullingFrequencyInMs: _nullishCoalesce(_optionalChain([pulling, 'optionalAccess', _108 => _108.pullingFrequencyInMs]), () => ( DefaultSQLiteEventStoreProcessorPullingFrequencyInMs)),
2289
- signal: abortController.signal
2290
- });
2291
- start = (async () => {
2292
- if (!isRunning) return;
2293
- if (!isInitialized) {
2294
- await init();
2295
- }
2296
- const startFrom = await pool.withConnection(
2297
- async (connection) => zipSQLiteEventStoreMessageBatchPullerStartFrom(
2298
- await Promise.all(
2299
- processors.map(async (o) => {
2300
- const result = await o.start({
2301
- execute: connection.execute,
2302
- connection
2303
- });
2304
- return result;
2305
- })
2306
- )
2307
- )
2308
- );
2309
- await messagePuller.start({ startFrom });
2310
- await stopProcessors();
2311
- isRunning = false;
2312
- })();
2313
- return start;
2314
- },
2315
- stop,
2316
- close: async () => {
2317
- await stop();
2318
- await pool.close();
2319
- }
2320
- };
2321
- };
2322
-
2323
- // src/eventStore/SQLiteEventStore.ts
2324
- var SQLiteEventStoreDefaultStreamVersion = 0n;
2325
- var getSQLiteEventStore = (options) => {
2326
- let autoGenerateSchema = false;
2327
- const serializer = JSONSerializer.from(options);
2328
- const pool = _nullishCoalesce(options.pool, () => ( _dumbo.dumbo.call(void 0, {
2329
- serialization: options.serialization,
2330
- transactionOptions: {
2331
- allowNestedTransactions: true,
2332
- mode: "session_based"
2333
- },
2334
- ...options.driver.mapToDumboOptions(options)
2335
- })));
2336
- let migrateSchema = void 0;
2337
- 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]);
2339
- 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";
2341
- }
2342
- const migrate = (connection) => {
2343
- if (!migrateSchema) {
2344
- migrateSchema = createEventStoreSchema(connection, {
2345
- onBeforeSchemaCreated: async (context) => {
2346
- for (const projection2 of inlineProjections) {
2347
- if (projection2.init) {
2348
- await projection2.init({
2349
- version: _nullishCoalesce(projection2.version, () => ( 1)),
2350
- registrationType: "async",
2351
- status: "active",
2352
- context: {
2353
- execute: context.connection.execute,
2354
- connection: context.connection,
2355
- driverType: options.driver.driverType
2356
- }
2357
- });
2358
- }
2359
- }
2360
- if (_optionalChain([options, 'access', _115 => _115.hooks, 'optionalAccess', _116 => _116.onBeforeSchemaCreated])) {
2361
- await options.hooks.onBeforeSchemaCreated(context);
2362
- }
2363
- },
2364
- onAfterSchemaCreated: _optionalChain([options, 'access', _117 => _117.hooks, 'optionalAccess', _118 => _118.onAfterSchemaCreated])
2365
- });
2366
- }
2367
- return migrateSchema;
2368
- };
2369
- const ensureSchemaExists = () => {
2370
- if (!autoGenerateSchema) return Promise.resolve();
2371
- return pool.withConnection((connection) => migrate(connection));
2372
- };
2373
- return {
2374
- async aggregateStream(streamName, options2) {
2375
- await ensureSchemaExists();
2376
- const { evolve, initialState, read } = options2;
2377
- const expectedStreamVersion = _optionalChain([read, 'optionalAccess', _119 => _119.expectedStreamVersion]);
2378
- let state = initialState();
2379
- if (typeof streamName !== "string") {
2380
- throw new Error("Stream name is not string");
2381
- }
2382
- const result = await readStream(
2383
- pool.execute,
2384
- streamName,
2385
- { ...read, serializer: _nullishCoalesce(_optionalChain([read, 'optionalAccess', _120 => _120.serialization, 'optionalAccess', _121 => _121.serializer]), () => ( serializer)) }
2386
- );
2387
- const currentStreamVersion = result.currentStreamVersion;
2388
- assertExpectedVersionMatchesCurrent(
2389
- currentStreamVersion,
2390
- expectedStreamVersion,
2391
- SQLiteEventStoreDefaultStreamVersion
2392
- );
2393
- for (const event of result.events) {
2394
- if (!event) continue;
2395
- state = evolve(state, event);
2396
- }
2397
- return {
2398
- currentStreamVersion,
2399
- state,
2400
- streamExists: result.streamExists
2401
- };
2402
- },
2403
- readStream: async (streamName, readOptions) => {
2404
- await ensureSchemaExists();
2405
- return readStream(pool.execute, streamName, {
2406
- ...readOptions,
2407
- serializer: _nullishCoalesce(_optionalChain([options, 'access', _122 => _122.serialization, 'optionalAccess', _123 => _123.serializer]), () => ( serializer))
2408
- });
2409
- },
2410
- appendToStream: async (streamName, events, appendOptions) => {
2411
- await ensureSchemaExists();
2412
- const [firstPart, ...rest] = streamName.split("-");
2413
- const streamType = firstPart && rest.length > 0 ? firstPart : unknownTag2;
2414
- const appendResult = await pool.withConnection(
2415
- (connection) => appendToStream(connection, streamName, streamType, events, {
2416
- ...appendOptions,
2417
- onBeforeCommit: async (messages, context) => {
2418
- if (inlineProjections.length > 0)
2419
- await handleProjections({
2420
- projections: inlineProjections,
2421
- events: messages,
2422
- execute: context.connection.execute,
2423
- connection: context.connection,
2424
- driverType: options.driver.driverType
2425
- });
2426
- if (onBeforeCommitHook)
2427
- await onBeforeCommitHook(messages, context);
2428
- }
2429
- }),
2430
- { readonly: false }
2431
- );
2432
- if (!appendResult.success)
2433
- throw new ExpectedVersionConflictError(
2434
- -1n,
2435
- //TODO: Return actual version in case of error
2436
- _nullishCoalesce(_optionalChain([appendOptions, 'optionalAccess', _124 => _124.expectedStreamVersion]), () => ( NO_CONCURRENCY_CHECK))
2437
- );
2438
- return {
2439
- nextExpectedStreamVersion: appendResult.nextStreamPosition,
2440
- lastEventGlobalPosition: appendResult.lastGlobalPosition,
2441
- createdNewStream: appendResult.nextStreamPosition >= BigInt(events.length)
2442
- };
2443
- },
2444
- async streamExists(streamName, options2) {
2445
- await ensureSchemaExists();
2446
- return streamExists(pool.execute, streamName, options2);
2447
- },
2448
- consumer: (consumerOptions) => sqliteEventStoreConsumer({
2449
- ..._nullishCoalesce(options, () => ( {})),
2450
- ..._nullishCoalesce(consumerOptions, () => ( {})),
2451
- pool
2452
- }),
2453
- async withSession(callback) {
2454
- return await pool.withConnection(async (connection) => {
2455
- const sessionStore = getSQLiteEventStore({
2456
- ...options,
2457
- pool: _dumbo.dumbo.call(void 0, {
2458
- ...options.driver.mapToDumboOptions(options),
2459
- connection,
2460
- serialization: options.serialization
2461
- }),
2462
- transactionOptions: {
2463
- allowNestedTransactions: true,
2464
- mode: "session_based"
2465
- },
2466
- schema: {
2467
- ...options.schema,
2468
- autoMigration: "None"
2469
- },
2470
- serialization: options.serialization
2471
- });
2472
- await ensureSchemaExists();
2473
- return callback({
2474
- eventStore: sessionStore,
2475
- close: () => Promise.resolve()
2476
- });
2477
- });
2478
- },
2479
- close: () => pool.close(),
2480
- schema: {
2481
- sql: () => schemaSQL.join(""),
2482
- print: () => console.log(schemaSQL.join("")),
2483
- migrate: () => pool.withConnection(migrate)
2484
- }
2485
- };
2486
- };
2487
-
2488
- // src/eventStore/schema/readStream.ts
2489
- var { identifier: identifier6 } = _dumbo.SQL;
2490
- var readStream = async (execute, streamId, options) => {
2491
- const { serializer } = options;
2492
- const fromCondition = options.from ? _dumbo.SQL`AND stream_position >= ${options.from}` : _dumbo.SQL.EMPTY;
2493
- const to = Number(
2494
- _nullishCoalesce(_optionalChain([options, 'optionalAccess', _125 => _125.to]), () => ( (_optionalChain([options, 'optionalAccess', _126 => _126.maxCount]) ? (_nullishCoalesce(options.from, () => ( 0n))) + options.maxCount : NaN)))
2495
- );
2496
- const toCondition = !isNaN(to) ? _dumbo.SQL`AND stream_position <= ${to}` : _dumbo.SQL.EMPTY;
2497
- const { rows: results } = await execute.query(
2498
- _dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
2499
- 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}
2501
- ORDER BY stream_position ASC`
2502
- );
2503
- const messages = results.map((row) => {
2504
- const rawEvent = {
2505
- type: row.message_type,
2506
- data: serializer.deserialize(row.message_data),
2507
- metadata: serializer.deserialize(row.message_metadata)
2508
- };
2509
- const metadata = {
2510
- ..."metadata" in rawEvent ? _nullishCoalesce(rawEvent.metadata, () => ( {})) : {},
2511
- messageId: row.message_id,
2512
- streamName: streamId,
2513
- streamPosition: BigInt(row.stream_position),
2514
- globalPosition: BigInt(row.global_position),
2515
- checkpoint: bigIntProcessorCheckpoint(BigInt(row.global_position))
2516
- };
2517
- const event = {
2518
- ...rawEvent,
2519
- kind: "Event",
2520
- metadata
2521
- };
2522
- return upcastRecordedMessage(event, _optionalChain([options, 'optionalAccess', _128 => _128.schema, 'optionalAccess', _129 => _129.versioning]));
2523
- });
2524
- return messages.length > 0 ? {
2525
- currentStreamVersion: messages[messages.length - 1].metadata.streamPosition,
2526
- events: messages,
2527
- streamExists: true
2528
- } : {
2529
- currentStreamVersion: SQLiteEventStoreDefaultStreamVersion,
2530
- events: [],
2531
- streamExists: false
2532
- };
2533
- };
2534
-
2535
- // src/eventStore/schema/storeProcessorCheckpoint.ts
2536
-
2537
-
2538
-
2539
-
2540
-
2541
-
2542
- var { identifier: identifier7 } = _dumbo.SQL;
769
+ //#endregion
770
+ //#region src/eventStore/consumers/sqliteProcessor.ts
771
+ const sqliteProcessingScope = () => {
772
+ const processingScope = async (handler, partialContext) => {
773
+ const connection = partialContext?.connection;
774
+ if (!connection) throw new _event_driven_io_emmett.EmmettError("Connection is required in context or options");
775
+ return connection.withTransaction(async (transaction) => {
776
+ return handler({
777
+ ...partialContext,
778
+ connection,
779
+ execute: transaction.execute
780
+ });
781
+ });
782
+ };
783
+ return processingScope;
784
+ };
785
+ const sqliteWorkflowProcessingScope = (messageStore) => {
786
+ const processingScope = async (handler, partialContext) => {
787
+ const connection = partialContext?.connection;
788
+ if (!connection) throw new _event_driven_io_emmett.EmmettError("Connection is required in context or options");
789
+ return connection.withTransaction(async (transaction) => {
790
+ return handler({
791
+ ...partialContext,
792
+ connection: Object.assign(connection, { messageStore }),
793
+ execute: transaction.execute
794
+ });
795
+ });
796
+ };
797
+ return processingScope;
798
+ };
799
+ const sqliteWorkflowProcessor = (options) => {
800
+ const { processorId = options.processorId ?? (0, _event_driven_io_emmett.getWorkflowId)({ workflowName: options.workflow.name ?? "unknown" }), processorInstanceId = (0, _event_driven_io_emmett.getProcessorInstanceId)(processorId), version = _event_driven_io_emmett.defaultProcessorVersion, partition = _event_driven_io_emmett.defaultProcessorPartition } = options;
801
+ const hooks = {
802
+ ...options.hooks ?? {},
803
+ onClose: options.hooks?.onClose
804
+ };
805
+ return (0, _event_driven_io_emmett.workflowProcessor)({
806
+ ...options,
807
+ processorId,
808
+ processorInstanceId,
809
+ version,
810
+ partition,
811
+ hooks,
812
+ processingScope: sqliteWorkflowProcessingScope(options.messageStore),
813
+ checkpoints: sqliteCheckpointer()
814
+ });
815
+ };
816
+ const sqliteReactor = (options) => {
817
+ const { processorId = options.processorId, processorInstanceId = (0, _event_driven_io_emmett.getProcessorInstanceId)(processorId), version = _event_driven_io_emmett.defaultProcessorVersion, partition = _event_driven_io_emmett.defaultProcessorPartition, hooks } = options;
818
+ return (0, _event_driven_io_emmett.reactor)({
819
+ ...options,
820
+ processorId,
821
+ processorInstanceId,
822
+ version,
823
+ partition,
824
+ hooks,
825
+ processingScope: sqliteProcessingScope(),
826
+ checkpoints: sqliteCheckpointer()
827
+ });
828
+ };
829
+ const sqliteProjector = (options) => {
830
+ const { processorId = (0, _event_driven_io_emmett.getProjectorId)({ projectionName: options.projection.name ?? "unknown" }), processorInstanceId = (0, _event_driven_io_emmett.getProcessorInstanceId)(processorId), version = _event_driven_io_emmett.defaultProcessorVersion, partition = _event_driven_io_emmett.defaultProcessorPartition } = options;
831
+ const hooks = {
832
+ ...options.hooks ?? {},
833
+ onInit: options.projection.init !== void 0 || options.hooks?.onInit ? async (context) => {
834
+ if (options.projection.init) await options.projection.init({
835
+ version: options.projection.version ?? version,
836
+ status: "active",
837
+ registrationType: "async",
838
+ context: {
839
+ ...context,
840
+ migrationOptions: options.migrationOptions
841
+ }
842
+ });
843
+ if (options.hooks?.onInit) await options.hooks.onInit({
844
+ ...context,
845
+ migrationOptions: options.migrationOptions
846
+ });
847
+ } : options.hooks?.onInit,
848
+ onClose: options.hooks?.onClose
849
+ };
850
+ return (0, _event_driven_io_emmett.projector)({
851
+ ...options,
852
+ processorId,
853
+ processorInstanceId,
854
+ version,
855
+ partition,
856
+ hooks,
857
+ processingScope: sqliteProcessingScope(),
858
+ checkpoints: sqliteCheckpointer()
859
+ });
860
+ };
861
+
862
+ //#endregion
863
+ //#region src/eventStore/consumers/sqliteEventStoreConsumer.ts
864
+ const sqliteEventStoreConsumer = (options) => {
865
+ let isRunning = false;
866
+ let isInitialized = false;
867
+ const { pulling } = options;
868
+ const processors = options.processors ?? [];
869
+ let abortController = null;
870
+ let start;
871
+ let messagePuller;
872
+ const startedAwaiter = (0, _event_driven_io_emmett.asyncAwaiter)();
873
+ const pool = options.pool ?? (0, _event_driven_io_dumbo.dumbo)({
874
+ serialization: options.serialization,
875
+ transactionOptions: {
876
+ allowNestedTransactions: true,
877
+ mode: "session_based"
878
+ },
879
+ ...options.driver.mapToDumboOptions(options)
880
+ });
881
+ const eachBatch = (messagesBatch) => pool.withConnection(async (connection) => {
882
+ const activeProcessors = processors.filter((s) => s.isActive);
883
+ if (activeProcessors.length === 0) return {
884
+ type: "STOP",
885
+ reason: "No active processors"
886
+ };
887
+ return (await Promise.allSettled(activeProcessors.map(async (s) => {
888
+ return await s.handle(messagesBatch, {
889
+ connection,
890
+ execute: connection.execute
891
+ });
892
+ }))).some((r) => r.status === "fulfilled" && r.value?.type !== "STOP") ? void 0 : { type: "STOP" };
893
+ });
894
+ const processorContext = {
895
+ execute: void 0,
896
+ connection: void 0
897
+ };
898
+ const stopProcessors = () => Promise.all(processors.map((p) => p.close(processorContext)));
899
+ const stop = async () => {
900
+ if (!isRunning) return;
901
+ isRunning = false;
902
+ if (messagePuller) {
903
+ abortController?.abort();
904
+ await messagePuller.stop();
905
+ }
906
+ await start;
907
+ messagePuller = void 0;
908
+ abortController = null;
909
+ await stopProcessors();
910
+ };
911
+ const init = async () => {
912
+ if (isInitialized) return;
913
+ const sqliteProcessors = processors;
914
+ await pool.withConnection(async (connection) => {
915
+ for (const processor of sqliteProcessors) if (processor.init) await processor.init({
916
+ ...processorContext,
917
+ connection,
918
+ execute: connection.execute
919
+ });
920
+ });
921
+ isInitialized = true;
922
+ };
923
+ return {
924
+ consumerId: options.consumerId ?? (0, uuid.v7)(),
925
+ get isRunning() {
926
+ return isRunning;
927
+ },
928
+ whenStarted: () => startedAwaiter.wait,
929
+ processors,
930
+ init,
931
+ reactor: (options) => {
932
+ const processor = sqliteReactor(options);
933
+ processors.push(processor);
934
+ return processor;
935
+ },
936
+ projector: (options) => {
937
+ const processor = sqliteProjector(options);
938
+ processors.push(processor);
939
+ return processor;
940
+ },
941
+ workflowProcessor: (processorOptions) => {
942
+ const messageStore = getSQLiteEventStore({
943
+ ...options,
944
+ pool,
945
+ schema: { autoMigration: "None" }
946
+ });
947
+ const processor = sqliteWorkflowProcessor({
948
+ ...processorOptions,
949
+ messageStore
950
+ });
951
+ processors.push(processor);
952
+ return processor;
953
+ },
954
+ start: () => {
955
+ if (isRunning) return start;
956
+ startedAwaiter.reset();
957
+ if (processors.length === 0) {
958
+ const error = new _event_driven_io_emmett.EmmettError("Cannot start consumer without at least a single processor");
959
+ startedAwaiter.reject(error);
960
+ return Promise.reject(error);
961
+ }
962
+ isRunning = true;
963
+ abortController = new AbortController();
964
+ start = (async () => {
965
+ if (!isRunning) return;
966
+ try {
967
+ messagePuller = sqliteEventStoreMessageBatchPuller({
968
+ stopWhen: options.stopWhen,
969
+ executor: pool.execute,
970
+ eachBatch,
971
+ batchSize: pulling?.batchSize ?? 100,
972
+ pullingFrequencyInMs: pulling?.pullingFrequencyInMs ?? 50,
973
+ signal: abortController.signal
974
+ });
975
+ if (!isInitialized) await init();
976
+ const startFrom = await pool.withConnection(async (connection) => zipSQLiteEventStoreMessageBatchPullerStartFrom(await Promise.all(processors.map(async (o) => {
977
+ return await o.start({
978
+ execute: connection.execute,
979
+ connection
980
+ });
981
+ }))));
982
+ await messagePuller.start({
983
+ startFrom,
984
+ started: startedAwaiter
985
+ });
986
+ } catch (error) {
987
+ isRunning = false;
988
+ startedAwaiter.reject(error);
989
+ throw error;
990
+ } finally {
991
+ await stopProcessors();
992
+ }
993
+ })();
994
+ return start;
995
+ },
996
+ stop,
997
+ close: async () => {
998
+ await stop();
999
+ await pool.close();
1000
+ }
1001
+ };
1002
+ };
1003
+
1004
+ //#endregion
1005
+ //#region src/eventStore/SQLiteEventStore.ts
1006
+ const SQLiteEventStoreDefaultStreamVersion = 0n;
1007
+ const getSQLiteEventStore = (options) => {
1008
+ let autoGenerateSchema = false;
1009
+ const serializer = _event_driven_io_emmett.JSONSerializer.from(options);
1010
+ const pool = options.pool ?? (0, _event_driven_io_dumbo.dumbo)({
1011
+ serialization: options.serialization,
1012
+ transactionOptions: {
1013
+ allowNestedTransactions: true,
1014
+ mode: "session_based"
1015
+ },
1016
+ ...options.driver.mapToDumboOptions(options)
1017
+ });
1018
+ let migrateSchema = void 0;
1019
+ const inlineProjections = (options.projections ?? []).filter(({ type }) => type === "inline").map(({ projection }) => projection);
1020
+ const onBeforeCommitHook = options.hooks?.onBeforeCommit;
1021
+ if (options) autoGenerateSchema = options.schema?.autoMigration === void 0 || options.schema?.autoMigration !== "None";
1022
+ const migrate = (connection) => {
1023
+ if (!migrateSchema) migrateSchema = createEventStoreSchema(connection, {
1024
+ onBeforeSchemaCreated: async (context) => {
1025
+ for (const projection of inlineProjections) if (projection.init) await projection.init({
1026
+ version: projection.version ?? 1,
1027
+ registrationType: "async",
1028
+ status: "active",
1029
+ context: {
1030
+ execute: context.connection.execute,
1031
+ connection: context.connection,
1032
+ driverType: options.driver.driverType
1033
+ }
1034
+ });
1035
+ if (options.hooks?.onBeforeSchemaCreated) await options.hooks.onBeforeSchemaCreated(context);
1036
+ },
1037
+ onAfterSchemaCreated: options.hooks?.onAfterSchemaCreated
1038
+ });
1039
+ return migrateSchema;
1040
+ };
1041
+ const ensureSchemaExists = () => {
1042
+ if (!autoGenerateSchema) return Promise.resolve();
1043
+ return pool.withConnection((connection) => migrate(connection));
1044
+ };
1045
+ return {
1046
+ async aggregateStream(streamName, options) {
1047
+ await ensureSchemaExists();
1048
+ const { evolve, initialState, read } = options;
1049
+ const expectedStreamVersion = read?.expectedStreamVersion;
1050
+ let state = initialState();
1051
+ if (typeof streamName !== "string") throw new Error("Stream name is not string");
1052
+ const result = await readStream(pool.execute, streamName, {
1053
+ ...read,
1054
+ serializer: read?.serialization?.serializer ?? serializer
1055
+ });
1056
+ const currentStreamVersion = result.currentStreamVersion;
1057
+ (0, _event_driven_io_emmett.assertExpectedVersionMatchesCurrent)(currentStreamVersion, expectedStreamVersion, SQLiteEventStoreDefaultStreamVersion);
1058
+ for (const event of result.events) {
1059
+ if (!event) continue;
1060
+ state = evolve(state, event);
1061
+ }
1062
+ return {
1063
+ currentStreamVersion,
1064
+ state,
1065
+ streamExists: result.streamExists
1066
+ };
1067
+ },
1068
+ readStream: async (streamName, readOptions) => {
1069
+ await ensureSchemaExists();
1070
+ return readStream(pool.execute, streamName, {
1071
+ ...readOptions,
1072
+ serializer: options.serialization?.serializer ?? serializer
1073
+ });
1074
+ },
1075
+ appendToStream: async (streamName, events, appendOptions) => {
1076
+ await ensureSchemaExists();
1077
+ const [firstPart, ...rest] = streamName.split("-");
1078
+ const streamType = firstPart && rest.length > 0 ? firstPart : unknownTag;
1079
+ const appendResult = await pool.withConnection((connection) => appendToStream(connection, streamName, streamType, events, {
1080
+ ...appendOptions,
1081
+ onBeforeCommit: async (messages, context) => {
1082
+ if (inlineProjections.length > 0) await handleProjections({
1083
+ projections: inlineProjections,
1084
+ events: messages,
1085
+ execute: context.connection.execute,
1086
+ connection: context.connection,
1087
+ driverType: options.driver.driverType
1088
+ });
1089
+ if (onBeforeCommitHook) await onBeforeCommitHook(messages, context);
1090
+ }
1091
+ }), { readonly: false });
1092
+ if (!appendResult.success) throw new _event_driven_io_emmett.ExpectedVersionConflictError(-1n, appendOptions?.expectedStreamVersion ?? _event_driven_io_emmett.NO_CONCURRENCY_CHECK);
1093
+ return {
1094
+ nextExpectedStreamVersion: appendResult.nextStreamPosition,
1095
+ lastEventGlobalPosition: appendResult.lastGlobalPosition,
1096
+ createdNewStream: appendResult.nextStreamPosition >= BigInt(events.length)
1097
+ };
1098
+ },
1099
+ async streamExists(streamName, options) {
1100
+ await ensureSchemaExists();
1101
+ return streamExists(pool.execute, streamName, options);
1102
+ },
1103
+ consumer: (consumerOptions) => sqliteEventStoreConsumer({
1104
+ ...options ?? {},
1105
+ ...consumerOptions ?? {},
1106
+ pool
1107
+ }),
1108
+ async withSession(callback) {
1109
+ return await pool.withConnection(async (connection) => {
1110
+ const sessionStore = getSQLiteEventStore({
1111
+ ...options,
1112
+ pool: (0, _event_driven_io_dumbo.dumbo)({
1113
+ ...options.driver.mapToDumboOptions(options),
1114
+ connection,
1115
+ serialization: options.serialization
1116
+ }),
1117
+ transactionOptions: {
1118
+ allowNestedTransactions: true,
1119
+ mode: "session_based"
1120
+ },
1121
+ schema: {
1122
+ ...options.schema,
1123
+ autoMigration: "None"
1124
+ },
1125
+ serialization: options.serialization
1126
+ });
1127
+ await ensureSchemaExists();
1128
+ return callback({
1129
+ eventStore: sessionStore,
1130
+ close: () => Promise.resolve()
1131
+ });
1132
+ });
1133
+ },
1134
+ close: () => pool.close(),
1135
+ schema: {
1136
+ sql: () => schemaSQL.join(""),
1137
+ print: () => console.log(schemaSQL.join("")),
1138
+ migrate: () => pool.withConnection(migrate)
1139
+ }
1140
+ };
1141
+ };
1142
+
1143
+ //#endregion
1144
+ //#region src/eventStore/schema/readStream.ts
1145
+ const { identifier: identifier$2 } = _event_driven_io_dumbo.SQL;
1146
+ const readStream = async (execute, streamId, options) => {
1147
+ const { serializer } = options;
1148
+ const fromCondition = options.from ? _event_driven_io_dumbo.SQL`AND stream_position >= ${options.from}` : _event_driven_io_dumbo.SQL.EMPTY;
1149
+ const to = Number(options?.to ?? (options?.maxCount ? (options.from ?? 0n) + options.maxCount : NaN));
1150
+ const toCondition = !isNaN(to) ? _event_driven_io_dumbo.SQL`AND stream_position <= ${to}` : _event_driven_io_dumbo.SQL.EMPTY;
1151
+ const { rows: results } = await execute.query(_event_driven_io_dumbo.SQL`SELECT stream_id, stream_position, global_position, message_data, message_metadata, message_schema_version, message_type, message_id
1152
+ FROM ${identifier$2(messagesTable.name)}
1153
+ WHERE stream_id = ${streamId} AND partition = ${options?.partition ?? defaultTag} AND is_archived = FALSE ${fromCondition} ${toCondition}
1154
+ ORDER BY stream_position ASC`);
1155
+ const messages = results.map((row) => {
1156
+ const rawEvent = {
1157
+ type: row.message_type,
1158
+ data: serializer.deserialize(row.message_data),
1159
+ metadata: serializer.deserialize(row.message_metadata)
1160
+ };
1161
+ const metadata = {
1162
+ ..."metadata" in rawEvent ? rawEvent.metadata ?? {} : {},
1163
+ messageId: row.message_id,
1164
+ streamName: streamId,
1165
+ streamPosition: BigInt(row.stream_position),
1166
+ globalPosition: BigInt(row.global_position),
1167
+ checkpoint: (0, _event_driven_io_emmett.bigIntProcessorCheckpoint)(BigInt(row.global_position))
1168
+ };
1169
+ return (0, _event_driven_io_emmett.upcastRecordedMessage)({
1170
+ ...rawEvent,
1171
+ kind: "Event",
1172
+ metadata
1173
+ }, options?.schema?.versioning);
1174
+ });
1175
+ return messages.length > 0 ? {
1176
+ currentStreamVersion: messages[messages.length - 1].metadata.streamPosition,
1177
+ events: messages,
1178
+ streamExists: true
1179
+ } : {
1180
+ currentStreamVersion: SQLiteEventStoreDefaultStreamVersion,
1181
+ events: [],
1182
+ streamExists: false
1183
+ };
1184
+ };
1185
+
1186
+ //#endregion
1187
+ //#region src/eventStore/schema/storeProcessorCheckpoint.ts
1188
+ const { identifier: identifier$1 } = _event_driven_io_dumbo.SQL;
2543
1189
  async function storeSubscriptionCheckpointSQLite(execute, processorId, version, position, checkPosition, partition, processorInstanceId) {
2544
- processorInstanceId ??= unknownTag2;
2545
- if (checkPosition !== null) {
2546
- const updateResult = await execute.command(
2547
- _dumbo.SQL`
2548
- UPDATE ${identifier7(processorsTable.name)}
1190
+ processorInstanceId ??= unknownTag;
1191
+ if (checkPosition !== null) {
1192
+ const updateResult = await execute.command(_event_driven_io_dumbo.SQL`
1193
+ UPDATE ${identifier$1(processorsTable.name)}
2549
1194
  SET
2550
1195
  last_processed_checkpoint = ${position},
2551
1196
  processor_instance_id = ${processorInstanceId}
2552
1197
  WHERE processor_id = ${processorId}
2553
1198
  AND last_processed_checkpoint = ${checkPosition}
2554
1199
  AND partition = ${partition}
2555
- `
2556
- );
2557
- if (updateResult.rowCount && updateResult.rowCount > 0) {
2558
- return 1;
2559
- }
2560
- const current_position = await _dumbo.singleOrNull.call(void 0,
2561
- execute.query(
2562
- _dumbo.SQL`
2563
- SELECT last_processed_checkpoint FROM ${identifier7(processorsTable.name)}
2564
- WHERE processor_id = ${processorId} AND partition = ${partition}`
2565
- )
2566
- );
2567
- const currentPosition = current_position && _optionalChain([current_position, 'optionalAccess', _130 => _130.last_processed_checkpoint]) !== null ? current_position.last_processed_checkpoint : null;
2568
- if (currentPosition === position) {
2569
- return 0;
2570
- } else if (position !== null && currentPosition !== null && currentPosition > position) {
2571
- return 2;
2572
- } else {
2573
- return 2;
2574
- }
2575
- } else {
2576
- try {
2577
- await execute.command(
2578
- _dumbo.SQL`INSERT INTO ${identifier7(processorsTable.name)} (processor_id, version, last_processed_checkpoint, partition, processor_instance_id)
2579
- VALUES (${processorId}, ${version}, ${position}, ${partition}, ${processorInstanceId})`
2580
- );
2581
- return 1;
2582
- } catch (err) {
2583
- if (!_dumbo.DumboError.isInstanceOf(err, {
2584
- errorType: _dumbo.UniqueConstraintError.ErrorType
2585
- })) {
2586
- throw err;
2587
- }
2588
- const current = await _dumbo.singleOrNull.call(void 0,
2589
- execute.query(
2590
- _dumbo.SQL`
2591
- SELECT last_processed_checkpoint FROM ${identifier7(processorsTable.name)}
2592
- WHERE processor_id = ${processorId} AND partition = ${partition}`
2593
- )
2594
- );
2595
- const currentPosition = current && _optionalChain([current, 'optionalAccess', _131 => _131.last_processed_checkpoint]) !== null ? BigInt(current.last_processed_checkpoint) : null;
2596
- if (currentPosition === position) {
2597
- return 0;
2598
- } else {
2599
- return 2;
2600
- }
2601
- }
2602
- }
1200
+ `);
1201
+ if (updateResult.rowCount && updateResult.rowCount > 0) return 1;
1202
+ const current_position = await (0, _event_driven_io_dumbo.singleOrNull)(execute.query(_event_driven_io_dumbo.SQL`
1203
+ SELECT last_processed_checkpoint FROM ${identifier$1(processorsTable.name)}
1204
+ WHERE processor_id = ${processorId} AND partition = ${partition}`));
1205
+ const currentPosition = current_position && current_position?.last_processed_checkpoint !== null ? current_position.last_processed_checkpoint : null;
1206
+ if (currentPosition === position) return 0;
1207
+ else if (position !== null && currentPosition !== null && currentPosition > position) return 2;
1208
+ else return 2;
1209
+ } else try {
1210
+ await execute.command(_event_driven_io_dumbo.SQL`INSERT INTO ${identifier$1(processorsTable.name)} (processor_id, version, last_processed_checkpoint, partition, processor_instance_id)
1211
+ VALUES (${processorId}, ${version}, ${position}, ${partition}, ${processorInstanceId})`);
1212
+ return 1;
1213
+ } catch (err) {
1214
+ if (!_event_driven_io_dumbo.DumboError.isInstanceOf(err, { errorType: _event_driven_io_dumbo.UniqueConstraintError.ErrorType })) throw err;
1215
+ const current = await (0, _event_driven_io_dumbo.singleOrNull)(execute.query(_event_driven_io_dumbo.SQL`
1216
+ SELECT last_processed_checkpoint FROM ${identifier$1(processorsTable.name)}
1217
+ WHERE processor_id = ${processorId} AND partition = ${partition}`));
1218
+ if ((current && current?.last_processed_checkpoint !== null ? BigInt(current.last_processed_checkpoint) : null) === position) return 0;
1219
+ else return 2;
1220
+ }
2603
1221
  }
2604
1222
  async function storeProcessorCheckpoint(execute, options) {
2605
- try {
2606
- const result = await storeSubscriptionCheckpointSQLite(
2607
- execute,
2608
- options.processorId,
2609
- _nullishCoalesce(options.version, () => ( 1)),
2610
- options.newCheckpoint,
2611
- options.lastProcessedCheckpoint,
2612
- _nullishCoalesce(options.partition, () => ( defaultTag2))
2613
- );
2614
- return result === 1 ? { success: true, newCheckpoint: options.newCheckpoint } : { success: false, reason: result === 0 ? "IGNORED" : "MISMATCH" };
2615
- } catch (error) {
2616
- console.log(error);
2617
- throw error;
2618
- }
1223
+ try {
1224
+ const result = await storeSubscriptionCheckpointSQLite(execute, options.processorId, options.version ?? 1, options.newCheckpoint, options.lastProcessedCheckpoint, options.partition ?? defaultTag);
1225
+ return result === 1 ? {
1226
+ success: true,
1227
+ newCheckpoint: options.newCheckpoint
1228
+ } : {
1229
+ success: false,
1230
+ reason: result === 0 ? "IGNORED" : "MISMATCH"
1231
+ };
1232
+ } catch (error) {
1233
+ console.log(error);
1234
+ throw error;
1235
+ }
2619
1236
  }
2620
1237
 
2621
- // src/eventStore/schema/streamExists.ts
2622
-
2623
- var streamExists = (execute, streamId, options) => _dumbo.exists.call(void 0,
2624
- execute.query(
2625
- _dumbo.SQL`SELECT EXISTS (
1238
+ //#endregion
1239
+ //#region src/eventStore/schema/streamExists.ts
1240
+ const streamExists = (execute, streamId, options) => (0, _event_driven_io_dumbo.exists)(execute.query(_event_driven_io_dumbo.SQL`SELECT EXISTS (
2626
1241
  SELECT 1
2627
- 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
2629
- `
2630
- )
2631
- );
2632
-
2633
- // src/eventStore/schema/tables.ts
2634
-
2635
- var { identifier: identifier8, plain: plain2 } = _dumbo.SQL;
2636
- var streamsTableSQL = _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier8(streamsTable.name)}(
1242
+ from ${_event_driven_io_dumbo.SQL.identifier(streamsTable.name)}
1243
+ WHERE stream_id = ${streamId} AND partition = ${options?.partition ?? defaultTag} AND is_archived = FALSE) as exists
1244
+ `));
1245
+
1246
+ //#endregion
1247
+ //#region src/eventStore/schema/tables.ts
1248
+ const { identifier, plain } = _event_driven_io_dumbo.SQL;
1249
+ const streamsTableSQL = _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier(streamsTable.name)}(
2637
1250
  stream_id TEXT NOT NULL,
2638
1251
  stream_position BIGINT NOT NULL DEFAULT 0,
2639
- partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1252
+ partition TEXT NOT NULL DEFAULT '${plain(globalTag)}',
2640
1253
  stream_type TEXT NOT NULL,
2641
1254
  stream_metadata JSONB NOT NULL,
2642
1255
  is_archived BOOLEAN NOT NULL DEFAULT FALSE,
2643
1256
  PRIMARY KEY (stream_id, partition, is_archived),
2644
1257
  UNIQUE (stream_id, partition, is_archived)
2645
1258
  );`;
2646
- var messagesTableSQL = _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier8(messagesTable.name)}(
1259
+ const messagesTableSQL = _event_driven_io_dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier(messagesTable.name)}(
2647
1260
  stream_id TEXT NOT NULL,
2648
1261
  stream_position BIGINT NOT NULL,
2649
- partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1262
+ partition TEXT NOT NULL DEFAULT '${plain(globalTag)}',
2650
1263
  message_kind CHAR(1) NOT NULL DEFAULT 'E',
2651
1264
  message_data JSONB NOT NULL,
2652
1265
  message_metadata JSONB NOT NULL,
@@ -2659,22 +1272,22 @@ var messagesTableSQL = _dumbo.SQL`CREATE TABLE IF NOT EXISTS ${identifier8(messa
2659
1272
  UNIQUE (stream_id, stream_position, partition, is_archived)
2660
1273
  );
2661
1274
  `;
2662
- var processorsTableSQL = _dumbo.SQL`
2663
- CREATE TABLE IF NOT EXISTS ${_dumbo.SQL.identifier(processorsTable.name)}(
1275
+ const processorsTableSQL = _event_driven_io_dumbo.SQL`
1276
+ CREATE TABLE IF NOT EXISTS ${_event_driven_io_dumbo.SQL.identifier(processorsTable.name)}(
2664
1277
  processor_id TEXT NOT NULL,
2665
1278
  version INTEGER NOT NULL DEFAULT 1,
2666
- partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1279
+ partition TEXT NOT NULL DEFAULT '${plain(globalTag)}',
2667
1280
  status TEXT NOT NULL DEFAULT 'stopped',
2668
1281
  last_processed_checkpoint TEXT NOT NULL,
2669
- processor_instance_id TEXT DEFAULT '${plain2(unknownTag2)}',
1282
+ processor_instance_id TEXT DEFAULT '${plain(unknownTag)}',
2670
1283
  PRIMARY KEY (processor_id, partition, version)
2671
1284
  );
2672
1285
  `;
2673
- var projectionsTableSQL = _dumbo.SQL`
2674
- CREATE TABLE IF NOT EXISTS ${_dumbo.SQL.identifier(projectionsTable.name)}(
1286
+ const projectionsTableSQL = _event_driven_io_dumbo.SQL`
1287
+ CREATE TABLE IF NOT EXISTS ${_event_driven_io_dumbo.SQL.identifier(projectionsTable.name)}(
2675
1288
  name TEXT NOT NULL,
2676
1289
  version INTEGER NOT NULL DEFAULT 1,
2677
- partition TEXT NOT NULL DEFAULT '${plain2(globalTag)}',
1290
+ partition TEXT NOT NULL DEFAULT '${plain(globalTag)}',
2678
1291
  type CHAR(1) NOT NULL,
2679
1292
  kind TEXT NOT NULL,
2680
1293
  status TEXT NOT NULL,
@@ -2682,73 +1295,67 @@ var projectionsTableSQL = _dumbo.SQL`
2682
1295
  PRIMARY KEY (name, partition, version)
2683
1296
  );
2684
1297
  `;
2685
- var schemaSQL = [
2686
- streamsTableSQL,
2687
- messagesTableSQL,
2688
- processorsTableSQL,
2689
- projectionsTableSQL
1298
+ const schemaSQL = [
1299
+ streamsTableSQL,
1300
+ messagesTableSQL,
1301
+ processorsTableSQL,
1302
+ projectionsTableSQL
2690
1303
  ];
2691
- var createEventStoreSchema = async (pool, hooks) => {
2692
- await pool.withTransaction(async (tx) => {
2693
- await migration_0_42_0_FromSubscriptionsToProcessors(tx.execute);
2694
- if (_optionalChain([hooks, 'optionalAccess', _133 => _133.onBeforeSchemaCreated])) {
2695
- await hooks.onBeforeSchemaCreated({
2696
- connection: tx.connection
2697
- });
2698
- }
2699
- await tx.execute.batchCommand(schemaSQL);
2700
- if (_optionalChain([hooks, 'optionalAccess', _134 => _134.onAfterSchemaCreated])) {
2701
- await hooks.onAfterSchemaCreated();
2702
- }
2703
- });
2704
- };
2705
-
2706
-
2707
-
2708
-
2709
-
2710
-
2711
-
2712
-
2713
-
2714
-
2715
-
2716
-
2717
-
2718
-
2719
-
2720
-
2721
-
2722
-
2723
-
2724
-
2725
-
2726
-
2727
-
2728
-
2729
-
2730
-
2731
-
2732
-
2733
-
2734
-
2735
-
2736
-
2737
-
2738
-
2739
-
2740
-
2741
-
2742
-
2743
-
2744
-
2745
-
2746
-
2747
-
2748
-
2749
-
2750
-
2751
-
2752
-
2753
- exports.SQLiteEventStoreDefaultStreamVersion = SQLiteEventStoreDefaultStreamVersion; exports.SQLiteProjectionSpec = SQLiteProjectionSpec; exports.appendToStream = appendToStream; exports.assertSQLQueryResultMatches = assertSQLQueryResultMatches; exports.createEventStoreSchema = createEventStoreSchema; exports.defaultTag = defaultTag2; exports.documentDoesNotExist = documentDoesNotExist; exports.documentExists = documentExists; exports.documentMatchingExists = documentMatchingExists; exports.documentsAreTheSame = documentsAreTheSame; exports.documentsMatchingHaveCount = documentsMatchingHaveCount; exports.emmettPrefix = emmettPrefix2; exports.eventInStream = eventInStream; exports.eventsInStream = eventsInStream; exports.expectPongoDocuments = expectPongoDocuments; exports.expectSQL = expectSQL; exports.getSQLiteEventStore = getSQLiteEventStore; exports.globalNames = globalNames; exports.globalTag = globalTag; exports.handleProjections = handleProjections; exports.messagesTable = messagesTable; exports.messagesTableSQL = messagesTableSQL; exports.migration_0_42_0_FromSubscriptionsToProcessors = migration_0_42_0_FromSubscriptionsToProcessors; exports.migration_0_42_0_SQLs = migration_0_42_0_SQLs; exports.newEventsInStream = newEventsInStream; exports.pongoMultiStreamProjection = pongoMultiStreamProjection; exports.pongoProjection = pongoProjection; exports.pongoSingleStreamProjection = pongoSingleStreamProjection; exports.processorsTable = processorsTable; exports.processorsTableSQL = processorsTableSQL; exports.projectionsTable = projectionsTable; exports.projectionsTableSQL = projectionsTableSQL; exports.readLastMessageGlobalPosition = readLastMessageGlobalPosition; exports.readMessagesBatch = readMessagesBatch; exports.readProcessorCheckpoint = readProcessorCheckpoint; exports.readStream = readStream; exports.schemaSQL = schemaSQL; exports.schema_0_41_0 = schema_0_41_0; exports.schema_0_42_0 = schema_0_42_0; exports.sqliteProjection = sqliteProjection; exports.sqliteRawBatchSQLProjection = sqliteRawBatchSQLProjection; exports.sqliteRawSQLProjection = sqliteRawSQLProjection; exports.storeProcessorCheckpoint = storeProcessorCheckpoint; exports.streamExists = streamExists; exports.streamsTable = streamsTable; exports.streamsTableSQL = streamsTableSQL; exports.unknownTag = unknownTag2;
1304
+ const createEventStoreSchema = async (pool, hooks) => {
1305
+ await pool.withTransaction(async (tx) => {
1306
+ await migration_0_42_0_FromSubscriptionsToProcessors(tx.execute);
1307
+ if (hooks?.onBeforeSchemaCreated) await hooks.onBeforeSchemaCreated({ connection: tx.connection });
1308
+ await tx.execute.batchCommand(schemaSQL);
1309
+ if (hooks?.onAfterSchemaCreated) await hooks.onAfterSchemaCreated();
1310
+ });
1311
+ };
1312
+
1313
+ //#endregion
1314
+ exports.SQLiteEventStoreDefaultStreamVersion = SQLiteEventStoreDefaultStreamVersion;
1315
+ exports.SQLiteProjectionSpec = SQLiteProjectionSpec;
1316
+ exports.appendToStream = appendToStream;
1317
+ exports.assertSQLQueryResultMatches = assertSQLQueryResultMatches;
1318
+ exports.createEventStoreSchema = createEventStoreSchema;
1319
+ exports.defaultTag = defaultTag;
1320
+ exports.documentDoesNotExist = documentDoesNotExist;
1321
+ exports.documentExists = documentExists;
1322
+ exports.documentMatchingExists = documentMatchingExists;
1323
+ exports.documentsAreTheSame = documentsAreTheSame;
1324
+ exports.documentsMatchingHaveCount = documentsMatchingHaveCount;
1325
+ exports.emmettPrefix = emmettPrefix;
1326
+ exports.eventInStream = eventInStream;
1327
+ exports.eventsInStream = eventsInStream;
1328
+ exports.expectPongoDocuments = expectPongoDocuments;
1329
+ exports.expectSQL = expectSQL;
1330
+ exports.getSQLiteEventStore = getSQLiteEventStore;
1331
+ exports.globalNames = globalNames;
1332
+ exports.globalTag = globalTag;
1333
+ exports.handleProjections = handleProjections;
1334
+ exports.messagesTable = messagesTable;
1335
+ exports.messagesTableSQL = messagesTableSQL;
1336
+ exports.migration_0_42_0_FromSubscriptionsToProcessors = migration_0_42_0_FromSubscriptionsToProcessors;
1337
+ exports.migration_0_42_0_SQLs = migration_0_42_0_SQLs;
1338
+ exports.newEventsInStream = newEventsInStream;
1339
+ exports.pongoMultiStreamProjection = pongoMultiStreamProjection;
1340
+ exports.pongoProjection = pongoProjection;
1341
+ exports.pongoSingleStreamProjection = pongoSingleStreamProjection;
1342
+ exports.processorsTable = processorsTable;
1343
+ exports.processorsTableSQL = processorsTableSQL;
1344
+ exports.projectionsTable = projectionsTable;
1345
+ exports.projectionsTableSQL = projectionsTableSQL;
1346
+ exports.readLastMessageGlobalPosition = readLastMessageGlobalPosition;
1347
+ exports.readMessagesBatch = readMessagesBatch;
1348
+ exports.readProcessorCheckpoint = readProcessorCheckpoint;
1349
+ exports.readStream = readStream;
1350
+ exports.schemaSQL = schemaSQL;
1351
+ exports.schema_0_41_0 = schema_0_41_0;
1352
+ exports.schema_0_42_0 = schema_0_42_0;
1353
+ exports.sqliteProjection = sqliteProjection;
1354
+ exports.sqliteRawBatchSQLProjection = sqliteRawBatchSQLProjection;
1355
+ exports.sqliteRawSQLProjection = sqliteRawSQLProjection;
1356
+ exports.storeProcessorCheckpoint = storeProcessorCheckpoint;
1357
+ exports.streamExists = streamExists;
1358
+ exports.streamsTable = streamsTable;
1359
+ exports.streamsTableSQL = streamsTableSQL;
1360
+ exports.unknownTag = unknownTag;
2754
1361
  //# sourceMappingURL=index.cjs.map