@event-driven-io/emmett-expressjs 0.20.2-alpha.4 → 0.20.2-alpha.5

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
@@ -6,9 +6,8 @@ var _express = require('express'); var _express2 = _interopRequireDefault(_expre
6
6
 
7
7
  var _http = require('http'); var _http2 = _interopRequireDefault(_http);
8
8
 
9
- // ../emmett/dist/chunk-3XBWME34.js
10
- var a = ((n) => (n.NOT_A_NONEMPTY_STRING = "NOT_A_NONEMPTY_STRING", n.NOT_A_POSITIVE_NUMBER = "NOT_A_POSITIVE_NUMBER", n.NOT_AN_UNSIGNED_BIGINT = "NOT_AN_UNSIGNED_BIGINT", n))(a || {});
11
- var s = (t) => typeof t == "number" && t === t;
9
+ // ../emmett/dist/chunk-AEEEXE2R.js
10
+ var isNumber = (val) => typeof val === "number" && val === val;
12
11
 
13
12
  // ../emmett/dist/index.js
14
13
  var _uuid = require('uuid');
@@ -28,14 +27,21 @@ var _asyncretry = require('async-retry'); var _asyncretry2 = _interopRequireDefa
28
27
 
29
28
 
30
29
 
31
- var O = (t, e = {}) => new S(t, e);
32
- var S = (_class = class extends _webstreamspolyfill.TransformStream {
33
- constructor(r2, n = {}) {
34
- super({ cancel: (o2) => {
35
- console.log("Stream was canceled. Reason:", o2), this.stopChecking();
36
- } });_class.prototype.__init.call(this);_class.prototype.__init2.call(this);;
37
- this.onNoActiveReaderCallback = r2;
38
- this.streamId = _nullishCoalesce(_optionalChain([n, 'optionalAccess', _ => _.streamId]), () => ( _uuid.v4.call(void 0, ))), this.onNoActiveReaderCallback = r2, this.startChecking(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _2 => _2.intervalCheckInMs]), () => ( 20)));
30
+
31
+
32
+ var notifyAboutNoActiveReadersStream = (onNoActiveReaderCallback, options = {}) => new NotifyAboutNoActiveReadersStream(onNoActiveReaderCallback, options);
33
+ var NotifyAboutNoActiveReadersStream = (_class = class extends _webstreamspolyfill.TransformStream {
34
+ constructor(onNoActiveReaderCallback, options = {}) {
35
+ super({
36
+ cancel: (reason) => {
37
+ console.log("Stream was canceled. Reason:", reason);
38
+ this.stopChecking();
39
+ }
40
+ });_class.prototype.__init.call(this);_class.prototype.__init2.call(this);;
41
+ this.onNoActiveReaderCallback = onNoActiveReaderCallback;
42
+ this.streamId = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.streamId]), () => ( _uuid.v4.call(void 0, )));
43
+ this.onNoActiveReaderCallback = onNoActiveReaderCallback;
44
+ this.startChecking(_nullishCoalesce(_optionalChain([options, 'optionalAccess', _3 => _3.intervalCheckInMs]), () => ( 20)));
39
45
  }
40
46
  __init() {this.checkInterval = null}
41
47
 
@@ -43,148 +49,275 @@ var S = (_class = class extends _webstreamspolyfill.TransformStream {
43
49
  get hasActiveSubscribers() {
44
50
  return !this._isStopped;
45
51
  }
46
- startChecking(r2) {
52
+ startChecking(interval) {
47
53
  this.checkInterval = setInterval(() => {
48
54
  this.checkNoActiveReader();
49
- }, r2);
55
+ }, interval);
50
56
  }
51
57
  stopChecking() {
52
- this.checkInterval && (clearInterval(this.checkInterval), this.checkInterval = null, this._isStopped = true, this.onNoActiveReaderCallback(this));
58
+ if (!this.checkInterval) return;
59
+ clearInterval(this.checkInterval);
60
+ this.checkInterval = null;
61
+ this._isStopped = true;
62
+ this.onNoActiveReaderCallback(this);
53
63
  }
54
64
  checkNoActiveReader() {
55
- !this.readable.locked && !this._isStopped && this.stopChecking();
65
+ if (!this.readable.locked && !this._isStopped) {
66
+ this.stopChecking();
67
+ }
56
68
  }
57
69
  }, _class);
58
- var w2 = async (t, e) => e === void 0 || e.retries === 0 ? t() : _asyncretry2.default.call(void 0, async (r2) => {
59
- try {
60
- return await t();
61
- } catch (n) {
62
- throw _optionalChain([e, 'optionalAccess', _3 => _3.shouldRetryError]) && !e.shouldRetryError(n) && r2(n), n;
70
+ var asyncRetry = async (fn, opts) => {
71
+ if (opts === void 0 || opts.retries === 0) return fn();
72
+ return _asyncretry2.default.call(void 0,
73
+ async (bail) => {
74
+ try {
75
+ return await fn();
76
+ } catch (error2) {
77
+ if (_optionalChain([opts, 'optionalAccess', _4 => _4.shouldRetryError]) && !opts.shouldRetryError(error2)) {
78
+ bail(error2);
79
+ }
80
+ throw error2;
81
+ }
82
+ },
83
+ _nullishCoalesce(opts, () => ( { retries: 0 }))
84
+ );
85
+ };
86
+ var ParseError = class extends Error {
87
+ constructor(text) {
88
+ super(`Cannot parse! ${text}`);
63
89
  }
64
- }, _nullishCoalesce(e, () => ( { retries: 0 })));
65
- var W = class extends Error {
66
- constructor(e) {
67
- super(`Cannot parse! ${e}`);
90
+ };
91
+ var JSONParser = {
92
+ stringify: (value, options) => {
93
+ return JSON.stringify(
94
+ _optionalChain([options, 'optionalAccess', _5 => _5.map]) ? options.map(value) : value,
95
+ //TODO: Consider adding support to DateTime and adding specific format to mark that's a bigint
96
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-return
97
+ (_, v) => typeof v === "bigint" ? v.toString() : v
98
+ );
99
+ },
100
+ parse: (text, options) => {
101
+ const parsed = JSON.parse(text, _optionalChain([options, 'optionalAccess', _6 => _6.reviver]));
102
+ if (_optionalChain([options, 'optionalAccess', _7 => _7.typeCheck]) && !_optionalChain([options, 'optionalAccess', _8 => _8.typeCheck, 'call', _9 => _9(parsed)]))
103
+ throw new ParseError(text);
104
+ return _optionalChain([options, 'optionalAccess', _10 => _10.map]) ? options.map(parsed) : parsed;
68
105
  }
69
106
  };
70
- var c2 = { stringify: (t, e) => JSON.stringify(_optionalChain([e, 'optionalAccess', _4 => _4.map]) ? e.map(t) : t, (r2, n) => typeof n == "bigint" ? n.toString() : n), parse: (t, e) => {
71
- let r2 = JSON.parse(t, _optionalChain([e, 'optionalAccess', _5 => _5.reviver]));
72
- if (_optionalChain([e, 'optionalAccess', _6 => _6.typeCheck]) && !_optionalChain([e, 'optionalAccess', _7 => _7.typeCheck, 'call', _8 => _8(r2)])) throw new W(t);
73
- return _optionalChain([e, 'optionalAccess', _9 => _9.map]) ? e.map(r2) : r2;
74
- } };
75
- var ae = (t) => new (0, _webstreamspolyfill.TransformStream)({ transform(e, r2) {
76
- t(e) && r2.enqueue(e);
77
- } });
78
- var se = (t) => new (0, _webstreamspolyfill.TransformStream)({ transform(e, r2) {
79
- r2.enqueue(t(e));
80
- } });
81
- var ie = (t, e) => new g2(t, e);
82
- var g2 = class extends _webstreamspolyfill.TransformStream {
107
+ var filter = (filter2) => new (0, _webstreamspolyfill.TransformStream)({
108
+ transform(chunk, controller) {
109
+ if (filter2(chunk)) {
110
+ controller.enqueue(chunk);
111
+ }
112
+ }
113
+ });
114
+ var map = (map2) => new (0, _webstreamspolyfill.TransformStream)({
115
+ transform(chunk, controller) {
116
+ controller.enqueue(map2(chunk));
117
+ }
118
+ });
119
+ var reduce = (reducer, initialValue) => new ReduceTransformStream(reducer, initialValue);
120
+ var ReduceTransformStream = class extends _webstreamspolyfill.TransformStream {
83
121
 
84
122
 
85
- constructor(e, r2) {
86
- super({ transform: (n) => {
87
- this.accumulator = this.reducer(this.accumulator, n);
88
- }, flush: (n) => {
89
- n.enqueue(this.accumulator), n.terminate();
90
- } }), this.accumulator = r2, this.reducer = e;
123
+ constructor(reducer, initialValue) {
124
+ super({
125
+ transform: (chunk) => {
126
+ this.accumulator = this.reducer(this.accumulator, chunk);
127
+ },
128
+ flush: (controller) => {
129
+ controller.enqueue(this.accumulator);
130
+ controller.terminate();
131
+ }
132
+ });
133
+ this.accumulator = initialValue;
134
+ this.reducer = reducer;
91
135
  }
92
136
  };
93
- var me = (t, e, r2 = { forever: true, minTimeout: 25 }) => new (0, _webstreamspolyfill.TransformStream)({ start(n) {
94
- w2(() => Ne(t, e, n), r2).catch((o2) => {
95
- n.error(o2);
96
- });
97
- } });
98
- var Ne = async (t, e, r2) => {
99
- let o2 = t().getReader();
137
+ var retryStream = (createSourceStream, handleChunk2, retryOptions = { forever: true, minTimeout: 25 }) => new (0, _webstreamspolyfill.TransformStream)({
138
+ start(controller) {
139
+ asyncRetry(
140
+ () => onRestream(createSourceStream, handleChunk2, controller),
141
+ retryOptions
142
+ ).catch((error2) => {
143
+ controller.error(error2);
144
+ });
145
+ }
146
+ });
147
+ var onRestream = async (createSourceStream, handleChunk2, controller) => {
148
+ const sourceStream = createSourceStream();
149
+ const reader = sourceStream.getReader();
100
150
  try {
101
- let a2;
151
+ let done;
102
152
  do {
103
- let i = await o2.read();
104
- a2 = i.done, await e(i, r2), a2 && r2.terminate();
105
- } while (!a2);
153
+ const result = await reader.read();
154
+ done = result.done;
155
+ await handleChunk2(result, controller);
156
+ if (done) {
157
+ controller.terminate();
158
+ }
159
+ } while (!done);
106
160
  } finally {
107
- o2.releaseLock();
161
+ reader.releaseLock();
108
162
  }
109
163
  };
110
- var de = (t) => new h(t);
111
- var h = (_class2 = class extends _webstreamspolyfill.TransformStream {
164
+ var skip = (limit) => new SkipTransformStream(limit);
165
+ var SkipTransformStream = (_class2 = class extends _webstreamspolyfill.TransformStream {
112
166
  __init3() {this.count = 0}
113
167
 
114
- constructor(e) {
115
- super({ transform: (r2, n) => {
116
- this.count++, this.count > this.skip && n.enqueue(r2);
117
- } });_class2.prototype.__init3.call(this);, this.skip = e;
168
+ constructor(skip2) {
169
+ super({
170
+ transform: (chunk, controller) => {
171
+ this.count++;
172
+ if (this.count > this.skip) {
173
+ controller.enqueue(chunk);
174
+ }
175
+ }
176
+ });_class2.prototype.__init3.call(this);;
177
+ this.skip = skip2;
118
178
  }
119
179
  }, _class2);
120
- var pe = (t) => new (0, _webstreamspolyfill.TransformStream)({ transform(e, r2) {
121
- r2.enqueue(e), t(e) && r2.terminate();
122
- } });
123
- var le = (t) => new (0, _webstreamspolyfill.TransformStream)({ async transform(e, r2) {
124
- if (!t(e)) {
125
- r2.enqueue(e);
126
- return;
180
+ var stopAfter = (stopCondition) => new (0, _webstreamspolyfill.TransformStream)({
181
+ transform(chunk, controller) {
182
+ controller.enqueue(chunk);
183
+ if (stopCondition(chunk)) {
184
+ controller.terminate();
185
+ }
186
+ }
187
+ });
188
+ var stopOn = (stopCondition) => new (0, _webstreamspolyfill.TransformStream)({
189
+ async transform(chunk, controller) {
190
+ if (!stopCondition(chunk)) {
191
+ controller.enqueue(chunk);
192
+ return;
193
+ }
194
+ await Promise.resolve();
195
+ controller.terminate();
127
196
  }
128
- await Promise.resolve(), r2.terminate();
129
- } });
130
- var ce = (t) => new C(t);
131
- var C = (_class3 = class extends _webstreamspolyfill.TransformStream {
197
+ });
198
+ var take = (limit) => new TakeTransformStream(limit);
199
+ var TakeTransformStream = (_class3 = class extends _webstreamspolyfill.TransformStream {
132
200
  __init4() {this.count = 0}
133
201
 
134
- constructor(e) {
135
- super({ transform: (r2, n) => {
136
- this.count < this.limit ? (this.count++, n.enqueue(r2)) : n.terminate();
137
- } });_class3.prototype.__init4.call(this);, this.limit = e;
202
+ constructor(limit) {
203
+ super({
204
+ transform: (chunk, controller) => {
205
+ if (this.count < this.limit) {
206
+ this.count++;
207
+ controller.enqueue(chunk);
208
+ } else {
209
+ controller.terminate();
210
+ }
211
+ }
212
+ });_class3.prototype.__init4.call(this);;
213
+ this.limit = limit;
138
214
  }
139
215
  }, _class3);
140
- var ue = (t) => new (0, _webstreamspolyfill.TransformStream)({ start(e) {
141
- let r2 = setTimeout(() => {
142
- e.terminate();
143
- }, t), n = e.terminate.bind(e);
144
- e.terminate = () => {
145
- clearTimeout(r2), n();
146
- };
147
- }, transform(e, r2) {
148
- r2.enqueue(e);
149
- } });
150
- var fe = { filter: ae, take: ce, TakeTransformStream: C, skip: de, SkipTransformStream: h, map: se, notifyAboutNoActiveReadersStream: O, NotifyAboutNoActiveReadersStream: S, reduce: ie, ReduceTransformStream: g2, retry: me, stopAfter: pe, stopOn: le, waitAtMost: ue };
151
- var { retry: Be } = fe;
152
- var p2 = class extends Error {
153
- constructor(e) {
154
- super(e);
216
+ var waitAtMost = (waitTimeInMs) => new (0, _webstreamspolyfill.TransformStream)({
217
+ start(controller) {
218
+ const timeoutId = setTimeout(() => {
219
+ controller.terminate();
220
+ }, waitTimeInMs);
221
+ const originalTerminate = controller.terminate.bind(controller);
222
+ controller.terminate = () => {
223
+ clearTimeout(timeoutId);
224
+ originalTerminate();
225
+ };
226
+ },
227
+ transform(chunk, controller) {
228
+ controller.enqueue(chunk);
229
+ }
230
+ });
231
+ var streamTransformations = {
232
+ filter,
233
+ take,
234
+ TakeTransformStream,
235
+ skip,
236
+ SkipTransformStream,
237
+ map,
238
+ notifyAboutNoActiveReadersStream,
239
+ NotifyAboutNoActiveReadersStream,
240
+ reduce,
241
+ ReduceTransformStream,
242
+ retry: retryStream,
243
+ stopAfter,
244
+ stopOn,
245
+ waitAtMost
246
+ };
247
+ var { retry: retry2 } = streamTransformations;
248
+ var AssertionError = class extends Error {
249
+ constructor(message) {
250
+ super(message);
155
251
  }
156
252
  };
157
- var ye = (t, e) => {
158
- let r2 = t, n = e;
159
- return U(r2), U(n), Object.keys(n).every((o2) => typeof n[o2] == "object" ? ye(r2[o2], n[o2]) : n[o2] === r2[o2]);
253
+ var isSubset = (superObj, subObj) => {
254
+ const sup = superObj;
255
+ const sub = subObj;
256
+ assertOk(sup);
257
+ assertOk(sub);
258
+ return Object.keys(sub).every((ele) => {
259
+ if (typeof sub[ele] == "object") {
260
+ return isSubset(sup[ele], sub[ele]);
261
+ }
262
+ return sub[ele] === sup[ele];
263
+ });
160
264
  };
161
- var po = (t) => {
162
- throw new p2(_nullishCoalesce(t, () => ( "That should not ever happened, right?")));
265
+ var assertFails = (message) => {
266
+ throw new AssertionError(_nullishCoalesce(message, () => ( "That should not ever happened, right?")));
163
267
  };
164
- var ve = (t, e, r2) => {
165
- if (!ye(t, e)) throw new p2(_nullishCoalesce(r2, () => ( `subObj:
166
- ${c2.stringify(e)}
268
+ var assertMatches = (actual, expected, message) => {
269
+ if (!isSubset(actual, expected))
270
+ throw new AssertionError(
271
+ _nullishCoalesce(message, () => ( `subObj:
272
+ ${JSONParser.stringify(expected)}
167
273
  is not subset of
168
- ${c2.stringify(t)}`)));
274
+ ${JSONParser.stringify(actual)}`))
275
+ );
169
276
  };
170
- function U(t, e) {
171
- if (!t) throw new p2(_nullishCoalesce(e, () => ( "Condition is not truthy")));
277
+ function assertOk(obj, message) {
278
+ if (!obj) throw new AssertionError(_nullishCoalesce(message, () => ( `Condition is not truthy`)));
172
279
  }
173
- function u(t, e, r2) {
174
- if (t !== e) throw new p2(`${_nullishCoalesce(r2, () => ( "Objects are not equal"))}:
175
- Expected: ${c2.stringify(t)}
176
- Actual:${c2.stringify(e)}`);
280
+ function assertEqual(expected, actual, message) {
281
+ if (expected !== actual)
282
+ throw new AssertionError(
283
+ `${_nullishCoalesce(message, () => ( "Objects are not equal"))}:
284
+ Expected: ${JSONParser.stringify(expected)}
285
+ Actual:${JSONParser.stringify(actual)}`
286
+ );
177
287
  }
178
- var wo = (t) => {
179
- let e = /* @__PURE__ */ new Map();
180
- return { async aggregateStream(r2, n) {
181
- return t.aggregateStream(r2, n);
182
- }, readStream(r2, n) {
183
- return t.readStream(r2, n);
184
- }, appendToStream: async (r2, n, o2) => {
185
- let a2 = await t.appendToStream(r2, n, o2), i = _nullishCoalesce(e.get(r2), () => ( [r2, []]));
186
- return e.set(r2, [r2, [...i[1], ...n]]), a2;
187
- }, appendedEvents: e, setup: async (r2, n) => t.appendToStream(r2, n) };
288
+ var WrapEventStore = (eventStore) => {
289
+ const appendedEvents = /* @__PURE__ */ new Map();
290
+ return {
291
+ async aggregateStream(streamName, options) {
292
+ return eventStore.aggregateStream(streamName, options);
293
+ },
294
+ readStream(streamName, options) {
295
+ return eventStore.readStream(streamName, options);
296
+ },
297
+ appendToStream: async (streamName, events, options) => {
298
+ const result = await eventStore.appendToStream(
299
+ streamName,
300
+ events,
301
+ options
302
+ );
303
+ const currentStream = _nullishCoalesce(appendedEvents.get(streamName), () => ( [streamName, []]));
304
+ appendedEvents.set(streamName, [
305
+ streamName,
306
+ [...currentStream[1], ...events]
307
+ ]);
308
+ return result;
309
+ },
310
+ appendedEvents,
311
+ setup: async (streamName, events) => {
312
+ return eventStore.appendToStream(streamName, events);
313
+ }
314
+ // streamEvents: (): ReadableStream<
315
+ // // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
316
+ // ReadEvent<Event, ReadEventMetadataType> | GlobalSubscriptionEvent
317
+ // > => {
318
+ // return eventStore.streamEvents();
319
+ // },
320
+ };
188
321
  };
189
322
 
190
323
  // src/middlewares/problemDetailsMiddleware.ts
@@ -197,7 +330,7 @@ var problemDetailsMiddleware = (mapError) => (error, request, response, _next) =
197
330
  };
198
331
  var defaulErrorToProblemDetailsMapping = (error) => {
199
332
  let statusCode = 500;
200
- if ("errorCode" in error && s(error.errorCode) && error.errorCode >= 100 && error.errorCode < 600) {
333
+ if ("errorCode" in error && isNumber(error.errorCode) && error.errorCode >= 100 && error.errorCode < 600) {
201
334
  statusCode = error.errorCode;
202
335
  }
203
336
  return new (0, _httpproblemdetails.ProblemDocument)({
@@ -364,7 +497,7 @@ var ApiE2ESpecification = {
364
497
  for: (getEventStore, getApplication2) => {
365
498
  {
366
499
  return (...givenRequests) => {
367
- const eventStore = wo(getEventStore());
500
+ const eventStore = WrapEventStore(getEventStore());
368
501
  const application = getApplication2(eventStore);
369
502
  return {
370
503
  when: (setupRequest) => {
@@ -404,9 +537,9 @@ var expectNewEvents = (streamId, events) => {
404
537
  };
405
538
  var expectResponse = (statusCode, options) => (response) => {
406
539
  const { body, headers } = _nullishCoalesce(options, () => ( {}));
407
- u(statusCode, response.statusCode, "Response code doesn't match");
408
- if (body) ve(response.body, body);
409
- if (headers) ve(response.headers, headers);
540
+ assertEqual(statusCode, response.statusCode, "Response code doesn't match");
541
+ if (body) assertMatches(response.body, body);
542
+ if (headers) assertMatches(response.headers, headers);
410
543
  };
411
544
  var expectError = (errorCode, problemDetails) => expectResponse(
412
545
  errorCode,
@@ -416,7 +549,7 @@ var ApiSpecification = {
416
549
  for: (getEventStore, getApplication2) => {
417
550
  {
418
551
  return (...givenStreams) => {
419
- const eventStore = wo(getEventStore());
552
+ const eventStore = WrapEventStore(getEventStore());
420
553
  const application = getApplication2(eventStore);
421
554
  return {
422
555
  when: (setupRequest) => {
@@ -431,15 +564,15 @@ var ApiSpecification = {
431
564
  const response = await handle();
432
565
  if (typeof verify === "function") {
433
566
  const succeeded = verify(response);
434
- if (succeeded === false) po();
567
+ if (succeeded === false) assertFails();
435
568
  } else if (Array.isArray(verify)) {
436
569
  const [first, ...rest] = verify;
437
570
  if (typeof first === "function") {
438
571
  const succeeded = first(response);
439
- if (succeeded === false) po();
572
+ if (succeeded === false) assertFails();
440
573
  }
441
574
  const events = typeof first === "function" ? rest : verify;
442
- ve(
575
+ assertMatches(
443
576
  Array.from(eventStore.appendedEvents.values()),
444
577
  events
445
578
  );