gingersnap 0.22.0

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.
Files changed (251) hide show
  1. package/_virtual/_tslib.cjs +102 -0
  2. package/_virtual/_tslib.mjs +93 -0
  3. package/data/AtomicValue.d.ts +15 -0
  4. package/data/bus.cjs +179 -0
  5. package/data/bus.d.ts +72 -0
  6. package/data/bus.mjs +177 -0
  7. package/data/decoders/index.d.ts +4 -0
  8. package/data/decoders/json.cjs +12 -0
  9. package/data/decoders/json.d.ts +7 -0
  10. package/data/decoders/json.mjs +10 -0
  11. package/data/decoders/msgpack.cjs +14 -0
  12. package/data/decoders/msgpack.d.ts +7 -0
  13. package/data/decoders/msgpack.mjs +12 -0
  14. package/data/decoders/protobuf.d.ts +13 -0
  15. package/data/decoders/string.cjs +12 -0
  16. package/data/decoders/string.d.ts +7 -0
  17. package/data/decoders/string.mjs +10 -0
  18. package/data/decoders/type.d.ts +7 -0
  19. package/data/decoders.cjs +11 -0
  20. package/data/decoders.mjs +3 -0
  21. package/data/model/credentials.cjs +114 -0
  22. package/data/model/credentials.d.ts +61 -0
  23. package/data/model/credentials.mjs +109 -0
  24. package/data/model/extra.cjs +88 -0
  25. package/data/model/extra.d.ts +5 -0
  26. package/data/model/extra.mjs +66 -0
  27. package/data/model/index.d.ts +6 -0
  28. package/data/model/model.cjs +541 -0
  29. package/data/model/model.d.ts +207 -0
  30. package/data/model/model.mjs +518 -0
  31. package/data/model/plugin.cjs +96 -0
  32. package/data/model/plugin.d.ts +38 -0
  33. package/data/model/plugin.mjs +72 -0
  34. package/data/model/property.cjs +310 -0
  35. package/data/model/property.d.ts +83 -0
  36. package/data/model/property.mjs +278 -0
  37. package/data/model/types.cjs +32 -0
  38. package/data/model/types.d.ts +28 -0
  39. package/data/model/types.mjs +32 -0
  40. package/data/model.cjs +43 -0
  41. package/data/model.mjs +6 -0
  42. package/data/signal.cjs +47 -0
  43. package/data/signal.d.ts +17 -0
  44. package/data/signal.mjs +45 -0
  45. package/data/store/index.d.ts +4 -0
  46. package/data/store/json.cjs +58 -0
  47. package/data/store/json.d.ts +18 -0
  48. package/data/store/json.mjs +56 -0
  49. package/data/store/manager.cjs +206 -0
  50. package/data/store/manager.d.ts +44 -0
  51. package/data/store/manager.mjs +203 -0
  52. package/data/store/web.cjs +92 -0
  53. package/data/store/web.d.ts +25 -0
  54. package/data/store/web.mjs +89 -0
  55. package/data/value.cjs +66 -0
  56. package/data/value.mjs +64 -0
  57. package/data-structures/array/CyclicalList.cjs +57 -0
  58. package/data-structures/array/CyclicalList.d.ts +12 -0
  59. package/data-structures/array/CyclicalList.mjs +55 -0
  60. package/data-structures/array/Pair.cjs +30 -0
  61. package/data-structures/array/Pair.d.ts +17 -0
  62. package/data-structures/array/Pair.mjs +27 -0
  63. package/data-structures/array/Stack.cjs +96 -0
  64. package/data-structures/array/Stack.d.ts +41 -0
  65. package/data-structures/array/Stack.mjs +94 -0
  66. package/data-structures/array/Triple.cjs +34 -0
  67. package/data-structures/array/Triple.d.ts +19 -0
  68. package/data-structures/array/Triple.mjs +31 -0
  69. package/data-structures/array/Tuple.d.ts +8 -0
  70. package/data-structures/array/index.d.ts +5 -0
  71. package/data-structures/array.cjs +15 -0
  72. package/data-structures/array.mjs +4 -0
  73. package/data-structures/object/BufferQueue.cjs +98 -0
  74. package/data-structures/object/BufferQueue.d.ts +21 -0
  75. package/data-structures/object/BufferQueue.mjs +77 -0
  76. package/data-structures/object/CyclicalObject.cjs +155 -0
  77. package/data-structures/object/CyclicalObject.d.ts +74 -0
  78. package/data-structures/object/CyclicalObject.mjs +134 -0
  79. package/data-structures/object/Queue.cjs +178 -0
  80. package/data-structures/object/Queue.d.ts +31 -0
  81. package/data-structures/object/Queue.mjs +176 -0
  82. package/data-structures/object/SimpleQueue.cjs +53 -0
  83. package/data-structures/object/SimpleQueue.d.ts +13 -0
  84. package/data-structures/object/SimpleQueue.mjs +51 -0
  85. package/data-structures/object/TimeableObject.cjs +73 -0
  86. package/data-structures/object/TimeableObject.d.ts +30 -0
  87. package/data-structures/object/TimeableObject.mjs +71 -0
  88. package/data-structures/object/WaitableObject.cjs +61 -0
  89. package/data-structures/object/WaitableObject.d.ts +29 -0
  90. package/data-structures/object/WaitableObject.mjs +59 -0
  91. package/data-structures/object/WatchableObject.cjs +251 -0
  92. package/data-structures/object/WatchableObject.d.ts +88 -0
  93. package/data-structures/object/WatchableObject.mjs +230 -0
  94. package/data-structures/object/index.d.ts +7 -0
  95. package/data-structures/object.cjs +23 -0
  96. package/data-structures/object.mjs +7 -0
  97. package/errors/AbortError.cjs +9 -0
  98. package/errors/AbortError.d.ts +5 -0
  99. package/errors/AbortError.mjs +7 -0
  100. package/errors/CallExecutionError.cjs +13 -0
  101. package/errors/CallExecutionError.d.ts +7 -0
  102. package/errors/CallExecutionError.mjs +11 -0
  103. package/errors/FutureCancelled.cjs +11 -0
  104. package/errors/FutureCancelled.d.ts +6 -0
  105. package/errors/FutureCancelled.mjs +9 -0
  106. package/errors/FutureError.cjs +11 -0
  107. package/errors/FutureError.d.ts +6 -0
  108. package/errors/FutureError.mjs +9 -0
  109. package/errors/IllegalArgumentsError.cjs +13 -0
  110. package/errors/IllegalArgumentsError.d.ts +7 -0
  111. package/errors/IllegalArgumentsError.mjs +11 -0
  112. package/errors/IllegalOperationError.cjs +6 -0
  113. package/errors/IllegalOperationError.d.ts +2 -0
  114. package/errors/IllegalOperationError.mjs +4 -0
  115. package/errors/InvalidType.cjs +6 -0
  116. package/errors/InvalidType.d.ts +2 -0
  117. package/errors/InvalidType.mjs +4 -0
  118. package/errors/InvalidValue.cjs +11 -0
  119. package/errors/InvalidValue.d.ts +4 -0
  120. package/errors/InvalidValue.mjs +9 -0
  121. package/errors/MissingArgumentsError.cjs +13 -0
  122. package/errors/MissingArgumentsError.d.ts +7 -0
  123. package/errors/MissingArgumentsError.mjs +11 -0
  124. package/errors/NetworkError.cjs +13 -0
  125. package/errors/NetworkError.d.ts +8 -0
  126. package/errors/NetworkError.mjs +11 -0
  127. package/errors/NoSuchElement.cjs +6 -0
  128. package/errors/NoSuchElement.d.ts +2 -0
  129. package/errors/NoSuchElement.mjs +4 -0
  130. package/errors/NotImplemented.cjs +9 -0
  131. package/errors/NotImplemented.d.ts +5 -0
  132. package/errors/NotImplemented.mjs +7 -0
  133. package/errors/ParsingError.cjs +10 -0
  134. package/errors/ParsingError.d.ts +5 -0
  135. package/errors/ParsingError.mjs +8 -0
  136. package/errors/QueueEmptyError.cjs +6 -0
  137. package/errors/QueueEmptyError.d.ts +2 -0
  138. package/errors/QueueEmptyError.mjs +4 -0
  139. package/errors/QueueFullError.cjs +6 -0
  140. package/errors/QueueFullError.d.ts +2 -0
  141. package/errors/QueueFullError.mjs +4 -0
  142. package/errors/StackEmptyError.cjs +6 -0
  143. package/errors/StackEmptyError.d.ts +2 -0
  144. package/errors/StackEmptyError.mjs +4 -0
  145. package/errors/StackFullError.cjs +6 -0
  146. package/errors/StackFullError.d.ts +2 -0
  147. package/errors/StackFullError.mjs +4 -0
  148. package/errors/StreamEnded.cjs +6 -0
  149. package/errors/StreamEnded.d.ts +2 -0
  150. package/errors/StreamEnded.mjs +4 -0
  151. package/errors/TimeoutError.cjs +11 -0
  152. package/errors/TimeoutError.d.ts +6 -0
  153. package/errors/TimeoutError.mjs +9 -0
  154. package/errors/ValueDestroyedError.cjs +6 -0
  155. package/errors/ValueDestroyedError.d.ts +2 -0
  156. package/errors/ValueDestroyedError.mjs +4 -0
  157. package/errors/VerificationError.cjs +9 -0
  158. package/errors/VerificationError.d.ts +5 -0
  159. package/errors/VerificationError.mjs +7 -0
  160. package/errors/index.d.ts +18 -0
  161. package/errors.cjs +41 -0
  162. package/errors.mjs +18 -0
  163. package/files.cjs +201 -0
  164. package/files.d.ts +31 -0
  165. package/files.mjs +180 -0
  166. package/functools/index.d.ts +31 -0
  167. package/functools.cjs +371 -0
  168. package/functools.mjs +334 -0
  169. package/future/future.cjs +570 -0
  170. package/future/future.d.ts +208 -0
  171. package/future/future.mjs +548 -0
  172. package/future/group.cjs +180 -0
  173. package/future/group.d.ts +82 -0
  174. package/future/group.mjs +159 -0
  175. package/future/index.d.ts +3 -0
  176. package/future/result.cjs +19 -0
  177. package/future/result.d.ts +18 -0
  178. package/future/result.mjs +17 -0
  179. package/future.cjs +11 -0
  180. package/future.mjs +3 -0
  181. package/managers/context.d.ts +8 -0
  182. package/managers/index.d.ts +1 -0
  183. package/managers.cjs +2 -0
  184. package/managers.mjs +1 -0
  185. package/mocks.cjs +301 -0
  186. package/mocks.d.ts +125 -0
  187. package/mocks.mjs +293 -0
  188. package/networking/EventSourceService.cjs +104 -0
  189. package/networking/EventSourceService.d.ts +11 -0
  190. package/networking/EventSourceService.mjs +83 -0
  191. package/networking/NetworkService.cjs +394 -0
  192. package/networking/NetworkService.d.ts +97 -0
  193. package/networking/NetworkService.mjs +373 -0
  194. package/networking/SocketService.cjs +218 -0
  195. package/networking/SocketService.d.ts +23 -0
  196. package/networking/SocketService.mjs +197 -0
  197. package/networking/decorators/index.d.ts +4 -0
  198. package/networking/decorators/options.cjs +289 -0
  199. package/networking/decorators/options.d.ts +148 -0
  200. package/networking/decorators/options.mjs +242 -0
  201. package/networking/decorators/requests.cjs +80 -0
  202. package/networking/decorators/requests.d.ts +34 -0
  203. package/networking/decorators/requests.mjs +52 -0
  204. package/networking/decorators/socket.cjs +81 -0
  205. package/networking/decorators/socket.d.ts +13 -0
  206. package/networking/decorators/socket.mjs +51 -0
  207. package/networking/http.cjs +69 -0
  208. package/networking/http.d.ts +66 -0
  209. package/networking/http.mjs +69 -0
  210. package/networking/index.d.ts +39 -0
  211. package/networking/request.cjs +18 -0
  212. package/networking/request.d.ts +9 -0
  213. package/networking/request.mjs +16 -0
  214. package/networking/types.cjs +37 -0
  215. package/networking/types.d.ts +132 -0
  216. package/networking/types.mjs +35 -0
  217. package/networking.cjs +91 -0
  218. package/networking.mjs +33 -0
  219. package/package.json +1 -0
  220. package/reflection/injector.cjs +43 -0
  221. package/reflection/injector.d.ts +3 -0
  222. package/reflection/injector.mjs +40 -0
  223. package/socket.cjs +239 -0
  224. package/socket.d.ts +65 -0
  225. package/socket.mjs +237 -0
  226. package/store.cjs +12 -0
  227. package/store.mjs +3 -0
  228. package/stream/call.cjs +157 -0
  229. package/stream/call.d.ts +66 -0
  230. package/stream/call.mjs +154 -0
  231. package/stream/collector.cjs +217 -0
  232. package/stream/collector.d.ts +14 -0
  233. package/stream/collector.mjs +215 -0
  234. package/stream/index.d.ts +257 -0
  235. package/stream/observable.cjs +110 -0
  236. package/stream/observable.d.ts +65 -0
  237. package/stream/observable.mjs +106 -0
  238. package/stream/state.cjs +10 -0
  239. package/stream/state.d.ts +5 -0
  240. package/stream/state.mjs +8 -0
  241. package/stream.cjs +1153 -0
  242. package/stream.mjs +1132 -0
  243. package/synchronize.cjs +106 -0
  244. package/synchronize.d.ts +54 -0
  245. package/synchronize.mjs +103 -0
  246. package/typing/types.d.ts +24 -0
  247. package/typing.cjs +2 -0
  248. package/typing.mjs +1 -0
  249. package/utils/parser.cjs +37 -0
  250. package/utils/parser.d.ts +7 -0
  251. package/utils/parser.mjs +16 -0
package/stream.cjs ADDED
@@ -0,0 +1,1153 @@
1
+ 'use strict';
2
+
3
+ var _tslib = require('./_virtual/_tslib.cjs');
4
+ var CallExecutionError = require('./errors/CallExecutionError.cjs');
5
+ var FutureCancelled = require('./errors/FutureCancelled.cjs');
6
+ var FutureError = require('./errors/FutureError.cjs');
7
+ var StreamEnded = require('./errors/StreamEnded.cjs');
8
+ var R = require('ramda');
9
+ var future = require('./future/future.cjs');
10
+ var result = require('./future/result.cjs');
11
+ var synchronize = require('./synchronize.cjs');
12
+ var stream_state = require('./stream/state.cjs');
13
+ var TimeableObject = require('./data-structures/object/TimeableObject.cjs');
14
+ var IllegalOperationError = require('./errors/IllegalOperationError.cjs');
15
+ require('./data-structures/object/WatchableObject.cjs');
16
+ require('uuid');
17
+ var Queue = require('./data-structures/object/Queue.cjs');
18
+ var data_value = require('./data/value.cjs');
19
+
20
+ function _interopNamespaceDefault(e) {
21
+ var n = Object.create(null);
22
+ if (e) {
23
+ Object.keys(e).forEach(function (k) {
24
+ if (k !== 'default') {
25
+ var d = Object.getOwnPropertyDescriptor(e, k);
26
+ Object.defineProperty(n, k, d.get ? d : {
27
+ enumerable: true,
28
+ get: function () { return e[k]; }
29
+ });
30
+ }
31
+ });
32
+ }
33
+ n.default = e;
34
+ return Object.freeze(n);
35
+ }
36
+
37
+ var R__namespace = /*#__PURE__*/_interopNamespaceDefault(R);
38
+
39
+ var ActionType;
40
+ (function (ActionType) {
41
+ ActionType[ActionType["TRANSFORM"] = 0] = "TRANSFORM";
42
+ ActionType[ActionType["FILTER"] = 1] = "FILTER";
43
+ ActionType[ActionType["LIMIT"] = 2] = "LIMIT";
44
+ ActionType[ActionType["UNPACK"] = 3] = "UNPACK";
45
+ ActionType[ActionType["PACK"] = 4] = "PACK";
46
+ ActionType[ActionType["CATCH"] = 5] = "CATCH";
47
+ })(ActionType || (ActionType = {}));
48
+ exports.State = void 0;
49
+ (function (State) {
50
+ State[State["MATCHED"] = 0] = "MATCHED";
51
+ State[State["CONTINUE"] = 1] = "CONTINUE";
52
+ State[State["DONE"] = 2] = "DONE";
53
+ })(exports.State || (exports.State = {}));
54
+ /**
55
+ * Handles a continuous supply of data that can be transformed and manipulated using a chain of actions
56
+ */
57
+ class Stream {
58
+ constructor(executor) {
59
+ this.executor = executor;
60
+ this.controller = new AbortController();
61
+ this.executed = false;
62
+ this.done = false;
63
+ this.canRunExecutor = true;
64
+ this.actions = [];
65
+ this.backlog = [];
66
+ this.cancelHooks = new Set();
67
+ this.completionHooks = new Set();
68
+ this.completionHookInvoked = false;
69
+ this.runLock = new synchronize.Lock();
70
+ this.concurrencyLimit = 0;
71
+ }
72
+ /**
73
+ * Used to provide setup logic that should only be invoked once, when stream
74
+ * is starting. This setup logic must provide the actual data required, which
75
+ * can come from a Stream or Future
76
+ * @param supplier
77
+ */
78
+ static seed(supplier) {
79
+ return new future.Future((resolve, reject, signal) => {
80
+ resolve(supplier());
81
+ }).stream;
82
+ }
83
+ /**
84
+ * Streams the next available result from a list of futures, until all future completes. If any future fails, then the
85
+ * stream will throw an error
86
+ * @param futures
87
+ */
88
+ static asCompleted(futures) {
89
+ const registerSignal = R__namespace.once((signal) => {
90
+ futures.forEach((future) => {
91
+ future.registerSignal(signal);
92
+ });
93
+ });
94
+ const launchFutures = R__namespace.once((futures) => {
95
+ const result = new Set();
96
+ for (let i = 0; i < futures.length; i++) {
97
+ const future = futures[i].clone();
98
+ result.add(future.thenApply((v) => [v.value, future], false));
99
+ }
100
+ return result;
101
+ });
102
+ return new Stream((signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
103
+ registerSignal(signal);
104
+ const promises = launchFutures(futures);
105
+ if (promises.size > 0) {
106
+ const result = yield Promise.race(promises);
107
+ const [value, future] = result;
108
+ promises.delete(future);
109
+ return value;
110
+ }
111
+ return new stream_state.ExecutorState(true);
112
+ }));
113
+ }
114
+ /**
115
+ * Stream the next available result from the list of streams. If any stream fails, then this merged stream also fails.
116
+ * @param streams
117
+ */
118
+ static merge(streams) {
119
+ const register = R__namespace.once((signal) => {
120
+ signal.onabort = () => streams.forEach((stream) => stream.cancel());
121
+ });
122
+ const buildFuture = (stream, index) => stream.future
123
+ .thenApply((v) => [v.value, index])
124
+ .catch((error) => {
125
+ if (error instanceof StreamEnded.StreamEnded) {
126
+ return [undefined, index];
127
+ }
128
+ throw error;
129
+ });
130
+ let streamCount = streams.length;
131
+ const futures = streams.map((stream, index) => buildFuture(stream, index));
132
+ return new Stream((signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
133
+ register(signal);
134
+ while (streamCount > 0) {
135
+ const [value, index] = yield future.Future.firstCompleted(futures);
136
+ if (value === undefined) {
137
+ futures[index] = new future.Future(() => { });
138
+ streamCount--;
139
+ }
140
+ else {
141
+ futures[index] = buildFuture(streams[index], index);
142
+ return value;
143
+ }
144
+ }
145
+ return new stream_state.ExecutorState(true);
146
+ }));
147
+ }
148
+ /**
149
+ * Aggregates the results from multiple streams
150
+ * @param streams
151
+ */
152
+ static zip(streams) {
153
+ const register = R__namespace.once((signal) => (signal.onabort = () => streams.forEach((stream) => stream.cancel())));
154
+ return new Stream((signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
155
+ register(signal);
156
+ try {
157
+ return yield future.Future.collect(streams.map((stream) => stream.future));
158
+ }
159
+ catch (error) {
160
+ if (error instanceof StreamEnded.StreamEnded) {
161
+ return new stream_state.ExecutorState(true);
162
+ }
163
+ throw error;
164
+ }
165
+ }));
166
+ }
167
+ /**
168
+ * Converts the provided value to a stream
169
+ * @param value
170
+ */
171
+ static of(value) {
172
+ if (value[Symbol.iterator]) {
173
+ const iterator = value[Symbol.iterator]();
174
+ return new Stream((signal) => {
175
+ if (!signal.aborted) {
176
+ const { value, done } = iterator.next();
177
+ return new stream_state.ExecutorState(done, value);
178
+ }
179
+ });
180
+ }
181
+ else if (value instanceof future.Future) {
182
+ let completed = false;
183
+ return new Stream((signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
184
+ if (completed) {
185
+ return new stream_state.ExecutorState(true);
186
+ }
187
+ value.registerSignal(signal);
188
+ completed = true;
189
+ return new stream_state.ExecutorState(false, yield value);
190
+ }));
191
+ }
192
+ const getIterator = value instanceof Function
193
+ ? R__namespace.once((v) => value(v))
194
+ : R__namespace.once((v) => value[Symbol.asyncIterator]());
195
+ return new Stream((signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
196
+ if (!signal.aborted) {
197
+ const iterator = getIterator(signal);
198
+ const { value, done } = yield iterator.next();
199
+ return new stream_state.ExecutorState(done, value);
200
+ }
201
+ }));
202
+ }
203
+ /**
204
+ * Stream that never gives a result
205
+ */
206
+ static forever() {
207
+ return new Stream(() => { });
208
+ }
209
+ get isParallel() {
210
+ return this.concurrencyLimit && this.sourceStream;
211
+ }
212
+ /**
213
+ * Gets a future of the next value on the stream, if any.
214
+ */
215
+ get future() {
216
+ return future.Future.of((resolve, reject, signal) => {
217
+ if (!signal.aborted) {
218
+ signal.onabort = () => this.cancel();
219
+ this.next()
220
+ .then((v) => {
221
+ if (v.done && v.value === undefined) {
222
+ reject(new StreamEnded.StreamEnded());
223
+ }
224
+ else {
225
+ resolve(v.value);
226
+ }
227
+ })
228
+ .catch(reject);
229
+ }
230
+ });
231
+ }
232
+ get readableStream() {
233
+ const iterator = this[Symbol.asyncIterator]();
234
+ return new ReadableStream({
235
+ pull(controller) {
236
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
237
+ const { value, done } = yield iterator.next();
238
+ if (done) {
239
+ controller.close();
240
+ }
241
+ else {
242
+ controller.enqueue(value);
243
+ }
244
+ });
245
+ },
246
+ });
247
+ }
248
+ /**
249
+ * Cancel the stream on the given signal
250
+ * @param signal
251
+ */
252
+ cancelOnSignal(signal) {
253
+ signal.addEventListener("abort", () => this.cancel());
254
+ return this;
255
+ }
256
+ parallel(concurrentlyLimit = 3) {
257
+ if (concurrentlyLimit < 1) {
258
+ throw new IllegalOperationError.IllegalOperationError("Cannot start parallel stream less than 2");
259
+ }
260
+ const newStream = new Stream(() => { });
261
+ newStream.concurrencyLimit = concurrentlyLimit;
262
+ newStream.sourceStream = this;
263
+ newStream.executed = this.executed;
264
+ newStream.done = this.done;
265
+ newStream.cancelHooks = new Set(this.cancelHooks);
266
+ newStream.completionHooks = new Set(this.completionHooks);
267
+ newStream.completionHookInvoked = this.completionHookInvoked;
268
+ return newStream;
269
+ }
270
+ /**
271
+ * Transforms each data on the stream using the callback provided
272
+ * @param callback
273
+ */
274
+ map(callback) {
275
+ this.actions.push({ type: ActionType.TRANSFORM, functor: callback });
276
+ return this;
277
+ }
278
+ /**
279
+ * Filters data on the stream using the callback provided
280
+ * @param callback
281
+ */
282
+ filter(callback) {
283
+ this.actions.push({
284
+ type: ActionType.FILTER,
285
+ functor: (v) => _tslib.__awaiter(this, void 0, void 0, function* () {
286
+ if (v instanceof result.FutureResult)
287
+ v = v.value;
288
+ let result$1 = callback(v);
289
+ if (result$1 instanceof Promise || result$1 instanceof future.Future)
290
+ result$1 = yield result$1;
291
+ if (result$1)
292
+ return v;
293
+ return null;
294
+ }),
295
+ });
296
+ return this;
297
+ }
298
+ reduce(initialData, functor, exhaustive = true) {
299
+ let previousData = initialData;
300
+ if (exhaustive) {
301
+ this.actions.push({
302
+ type: ActionType.PACK,
303
+ functor: (v) => {
304
+ if (v === null || v === undefined) {
305
+ return { done: true, value: previousData };
306
+ }
307
+ previousData = functor(v, previousData);
308
+ return { done: false };
309
+ },
310
+ });
311
+ }
312
+ else {
313
+ this.actions.push({
314
+ type: ActionType.TRANSFORM,
315
+ functor: (v) => {
316
+ previousData = functor(v, previousData);
317
+ return previousData;
318
+ },
319
+ });
320
+ }
321
+ return this;
322
+ }
323
+ reduceWhile(predicate, initialData, functor, exhaustive = true) {
324
+ let previousData = initialData;
325
+ if (exhaustive) {
326
+ this.actions.push({
327
+ type: ActionType.PACK,
328
+ functor: (v) => {
329
+ if (v === null || v === undefined || predicate(v)) {
330
+ return { done: true, value: previousData };
331
+ }
332
+ previousData = functor(v, previousData);
333
+ return { done: false };
334
+ },
335
+ });
336
+ }
337
+ else {
338
+ this.actions.push({
339
+ type: ActionType.LIMIT,
340
+ functor: (v) => {
341
+ if (predicate(v)) {
342
+ previousData = functor(v, previousData);
343
+ return { done: false, value: previousData };
344
+ }
345
+ return { done: true };
346
+ },
347
+ });
348
+ }
349
+ return this;
350
+ }
351
+ /**
352
+ * Retrieves the first value from the stream as a new stream. Important Note: the original stream cannot be executed
353
+ * before head() is invoked, otherwise the stream returned by head() will throw an error, as the first value was
354
+ * already consumed elsewhere
355
+ */
356
+ head() {
357
+ return new Stream(() => _tslib.__awaiter(this, void 0, void 0, function* () {
358
+ return new stream_state.ExecutorState(true, yield this.execute());
359
+ }));
360
+ }
361
+ /**
362
+ * Returns a new stream that exhausts the original stream, yielding the last value received before the original
363
+ * stream ended
364
+ */
365
+ tail() {
366
+ let lastRecord = null;
367
+ return new Stream(() => _tslib.__awaiter(this, void 0, void 0, function* () {
368
+ var _a, e_1, _b, _c;
369
+ try {
370
+ for (var _d = true, _e = _tslib.__asyncValues(this), _f; _f = yield _e.next(), _a = _f.done, !_a;) {
371
+ _c = _f.value;
372
+ _d = false;
373
+ try {
374
+ const value = _c;
375
+ lastRecord = value;
376
+ }
377
+ finally {
378
+ _d = true;
379
+ }
380
+ }
381
+ }
382
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
383
+ finally {
384
+ try {
385
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
386
+ }
387
+ finally { if (e_1) throw e_1.error; }
388
+ }
389
+ return new stream_state.ExecutorState(true, lastRecord);
390
+ }));
391
+ }
392
+ /**
393
+ * group data on the stream into separate slices
394
+ * E.g. Stream yielding 1,2,3,4,5,6 with chunk of 2 => [1,2], [3,4], [5,6]
395
+ * @param value chunk size or function that indicates when to split
396
+ * @param keepSplitCriteria if value provided was a function, this parameter is used to determine if the data used
397
+ * for the split criteria should be added to the chunk, if false then the data will be added to the next chunk
398
+ */
399
+ chunk(value, keepSplitCriteria = false) {
400
+ if (typeof value === "number" && value < 1)
401
+ throw new Error("Invalid chunk size");
402
+ let chunkedResults = [];
403
+ if (typeof value === "number") {
404
+ this.actions.push({
405
+ type: ActionType.PACK,
406
+ functor: (v) => {
407
+ if (v === undefined || v === null) {
408
+ return { done: true, value: chunkedResults.length > 0 ? chunkedResults : undefined };
409
+ }
410
+ chunkedResults.push(v);
411
+ if (chunkedResults.length >= value) {
412
+ const data = chunkedResults;
413
+ chunkedResults = [];
414
+ return { done: true, value: data };
415
+ }
416
+ return { done: false };
417
+ },
418
+ });
419
+ }
420
+ else {
421
+ this.actions.push({
422
+ type: ActionType.TRANSFORM,
423
+ functor: (v) => {
424
+ if (value(v)) {
425
+ if (keepSplitCriteria)
426
+ chunkedResults.push(v);
427
+ const data = chunkedResults;
428
+ chunkedResults = [];
429
+ return { done: true, value: data };
430
+ }
431
+ chunkedResults.push(v);
432
+ return { done: false };
433
+ },
434
+ });
435
+ }
436
+ return this;
437
+ }
438
+ /**
439
+ * Clones the stream
440
+ * @param withSignals should the abort signals of the original stream trigger the cloned stream cancellation
441
+ */
442
+ clone(withSignals) {
443
+ const newStream = new Stream(this.executor);
444
+ newStream.concurrencyLimit = this.concurrencyLimit;
445
+ newStream.sourceStream = this.sourceStream;
446
+ newStream.actions = [...this.actions];
447
+ newStream.executed = this.executed;
448
+ newStream.done = this.done;
449
+ newStream.backlog = [...this.backlog];
450
+ newStream.cancelHooks = new Set(this.cancelHooks);
451
+ newStream.completionHooks = new Set(this.completionHooks);
452
+ newStream.completionHookInvoked = this.completionHookInvoked;
453
+ if (withSignals) {
454
+ newStream.controller = this.controller;
455
+ }
456
+ return newStream;
457
+ }
458
+ /**
459
+ * Register hook that is only ever called if stream was cancelled
460
+ * @param hook
461
+ */
462
+ onCancellation(hook) {
463
+ this.cancelHooks.add(hook);
464
+ return this;
465
+ }
466
+ removeCancelHook(hook) {
467
+ this.cancelHooks.delete(hook);
468
+ return this;
469
+ }
470
+ /**
471
+ * Register hook that is called once the stream completes, cancelled or fails
472
+ * @param hook
473
+ */
474
+ onCompletion(hook) {
475
+ this.completionHooks.add(hook);
476
+ return this;
477
+ }
478
+ removeCompletionHook(hook) {
479
+ this.completionHooks.delete(hook);
480
+ return this;
481
+ }
482
+ /**
483
+ * Cancels the stream
484
+ * @param reason
485
+ */
486
+ cancel(reason) {
487
+ this.controller.abort(reason);
488
+ this.invokeCompletionHooks();
489
+ this.cancelHooks.forEach((handler) => {
490
+ void new Promise((resolve, reject) => {
491
+ try {
492
+ handler();
493
+ resolve(null);
494
+ }
495
+ catch (e) {
496
+ reject(e);
497
+ }
498
+ });
499
+ });
500
+ }
501
+ /**
502
+ * Limits the number of times the stream can yield a value
503
+ * @param count
504
+ */
505
+ take(count) {
506
+ let index = 0;
507
+ this.actions.push({
508
+ type: ActionType.LIMIT,
509
+ functor: (value) => {
510
+ if (++index < count) {
511
+ return { value, done: false };
512
+ }
513
+ return { done: true, value };
514
+ },
515
+ });
516
+ return this;
517
+ }
518
+ /**
519
+ * Process stream data while predicate is true
520
+ * @param predicate
521
+ */
522
+ takeWhile(predicate) {
523
+ this.actions.push({
524
+ type: ActionType.LIMIT,
525
+ functor: (value) => {
526
+ if (predicate(value)) {
527
+ return { value, done: false };
528
+ }
529
+ return { done: true };
530
+ },
531
+ });
532
+ return this;
533
+ }
534
+ /**
535
+ * Drop stream data until predicate is no longer true
536
+ * @param predicate
537
+ */
538
+ skipWhile(predicate) {
539
+ let startFound = false;
540
+ this.actions.push({
541
+ type: ActionType.FILTER,
542
+ functor: (value) => {
543
+ if (!startFound && predicate(value)) {
544
+ return null;
545
+ }
546
+ startFound = true;
547
+ return value;
548
+ },
549
+ });
550
+ return this;
551
+ }
552
+ /**
553
+ * Removes duplicates from the stream based on the key extractor functor provided
554
+ * @param uniqKeyExtractor
555
+ * @param expiryPeriod
556
+ */
557
+ dropRepeats(uniqKeyExtractor, expiryPeriod = undefined) {
558
+ const cache = new TimeableObject.TimeableObject(undefined, expiryPeriod);
559
+ this.actions.push({
560
+ type: ActionType.FILTER,
561
+ functor: (v) => _tslib.__awaiter(this, void 0, void 0, function* () {
562
+ const guid = uniqKeyExtractor(v);
563
+ if (!cache.has(guid)) {
564
+ cache.set(guid, 1);
565
+ return v;
566
+ }
567
+ return null;
568
+ }),
569
+ });
570
+ return this;
571
+ }
572
+ /**
573
+ * Allows the stream to yield only 1 value
574
+ */
575
+ once() {
576
+ return this.take(1);
577
+ }
578
+ /**
579
+ * Skips the first X records on the stream
580
+ * @param count
581
+ */
582
+ skip(count) {
583
+ let index = 1;
584
+ this.actions.push({
585
+ type: ActionType.FILTER,
586
+ functor: (value) => {
587
+ if (index && index++ <= count)
588
+ return null;
589
+ index = 0;
590
+ return value;
591
+ },
592
+ });
593
+ return this;
594
+ }
595
+ /**
596
+ * Applies rate limiting to the speed at which the data is made available on the stream
597
+ * @param period
598
+ */
599
+ throttleBy(period) {
600
+ let future$1;
601
+ this.actions.push({
602
+ type: ActionType.TRANSFORM,
603
+ functor: (value) => {
604
+ if (!future$1) {
605
+ future$1 = future.Future.sleep(period)
606
+ .thenApply(() => (future$1 = undefined))
607
+ .schedule();
608
+ return value;
609
+ }
610
+ return null;
611
+ },
612
+ });
613
+ return this;
614
+ }
615
+ /**
616
+ * Flattens any nested structure from the data arriving on the stream
617
+ */
618
+ flatten() {
619
+ this.actions.push({
620
+ type: ActionType.UNPACK,
621
+ functor: (value) => {
622
+ if (value instanceof Array || Array.isArray(value) || value instanceof Set)
623
+ return R__namespace.flatten(value);
624
+ return [value];
625
+ },
626
+ });
627
+ return this;
628
+ }
629
+ /**
630
+ * Runs the stream in the background, collecting and buffering the results for the next chain in the stream. This
631
+ * allows the stream to run concurrently without waiting on single emitted values sequentially
632
+ * @param maxSize
633
+ */
634
+ buffer(maxSize) {
635
+ return Stream.seed(() => {
636
+ const queue = new Queue.Queue(maxSize);
637
+ this.forEach((record) => queue.awaitEnqueue(record)).finally(() => {
638
+ queue
639
+ .awaitEmpty()
640
+ .thenApply(() => queue.close())
641
+ .schedule();
642
+ });
643
+ return queue.streamEntries.catch((error) => {
644
+ throw error;
645
+ });
646
+ });
647
+ }
648
+ /**
649
+ * Process stream values in the background, thereby yielding the latest value if the collector of the stream is too
650
+ * slow (i.e. values that are not read by collector before new value flows in the stream, will be dropped)
651
+ */
652
+ conflate() {
653
+ return Stream.seed(() => {
654
+ const value = new data_value.AtomicValue();
655
+ this.forEach((record) => value.set(record))
656
+ .finally(() => value.destroy())
657
+ .schedule();
658
+ return value.stream;
659
+ });
660
+ }
661
+ /**
662
+ * If the stream receives an error, handle that error with the given callback. If callback doesn't throw an error,
663
+ * then the stream will recover and resume with the result provided by the callback
664
+ * @param callback
665
+ */
666
+ catch(callback) {
667
+ this.actions.push({
668
+ type: ActionType.CATCH,
669
+ functor: callback,
670
+ });
671
+ return this;
672
+ }
673
+ /**
674
+ * Consumes the entire stream and store the data in an array. Future is immediately executed
675
+ */
676
+ collect(collector) {
677
+ return collector(this.isParallel ? this.join() : this).schedule();
678
+ }
679
+ /**
680
+ * Continuously exhaust the stream until the stream ends or the limit is reached. No result will be provided at
681
+ * the end. Future is immediately executed
682
+ * @param limit
683
+ */
684
+ consume(limit = Number.POSITIVE_INFINITY) {
685
+ return new future.Future((resolve, reject) => _tslib.__awaiter(this, void 0, void 0, function* () {
686
+ var _a, e_2, _b, _c, _d, e_3, _e, _f;
687
+ var _g;
688
+ try {
689
+ if (limit !== Number.POSITIVE_INFINITY && limit !== Number.NEGATIVE_INFINITY) {
690
+ if (limit === 0)
691
+ return;
692
+ let index = 0;
693
+ try {
694
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
695
+ for (var _h = true, _j = _tslib.__asyncValues(this), _k; _k = yield _j.next(), _a = _k.done, !_a;) {
696
+ _c = _k.value;
697
+ _h = false;
698
+ try {
699
+ const _ = _c;
700
+ if (++index >= limit)
701
+ break;
702
+ }
703
+ finally {
704
+ _h = true;
705
+ }
706
+ }
707
+ }
708
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
709
+ finally {
710
+ try {
711
+ if (!_h && !_a && (_b = _j.return)) yield _b.call(_j);
712
+ }
713
+ finally { if (e_2) throw e_2.error; }
714
+ }
715
+ }
716
+ else {
717
+ try {
718
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars,no-empty
719
+ for (var _l = true, _m = _tslib.__asyncValues(this), _o; _o = yield _m.next(), _d = _o.done, !_d;) {
720
+ _f = _o.value;
721
+ _l = false;
722
+ try {
723
+ const _ = _f;
724
+ }
725
+ finally {
726
+ _l = true;
727
+ }
728
+ }
729
+ }
730
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
731
+ finally {
732
+ try {
733
+ if (!_l && !_d && (_e = _m.return)) yield _e.call(_m);
734
+ }
735
+ finally { if (e_3) throw e_3.error; }
736
+ }
737
+ }
738
+ resolve();
739
+ }
740
+ catch (error) {
741
+ reject(error instanceof FutureError.FutureError ? error : new FutureError.FutureError((_g = error === null || error === void 0 ? void 0 : error.message) !== null && _g !== void 0 ? _g : "Unknown"));
742
+ }
743
+ })).schedule();
744
+ }
745
+ /**
746
+ * Iterates over the stream of values, used as a collector. Future is immediately executed
747
+ * @param callback
748
+ */
749
+ forEach(callback) {
750
+ return new future.Future((resolve, reject, signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
751
+ var _a;
752
+ try {
753
+ yield this.map((value) => callback(value))
754
+ .consume()
755
+ .registerSignal(signal);
756
+ resolve();
757
+ }
758
+ catch (error) {
759
+ reject(error instanceof FutureError.FutureError ? error : new FutureError.FutureError((_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : "Unknown"));
760
+ }
761
+ })).schedule();
762
+ }
763
+ /**
764
+ * Runs the stream only once. After this call, the stream is closed. Future is immediately executed
765
+ */
766
+ execute() {
767
+ return this.runLock
768
+ .with(({ signal }) => _tslib.__awaiter(this, void 0, void 0, function* () {
769
+ if (this.executed)
770
+ throw new CallExecutionError.CallExecutionError("Cannot rerun a one time stream");
771
+ while (true) {
772
+ const { state, value } = yield (this.sourceStream && this.concurrencyLimit
773
+ ? this.forwardExecute().registerSignal(signal)
774
+ : this.__execute__().registerSignal(signal));
775
+ if (state !== exports.State.CONTINUE) {
776
+ this.done = true;
777
+ this.invokeCompletionHooks();
778
+ return value;
779
+ }
780
+ }
781
+ }))
782
+ .schedule();
783
+ }
784
+ join() {
785
+ if (!this.concurrencyLimit || !this.sourceStream) {
786
+ throw new IllegalOperationError.IllegalOperationError("Join can only be called on a parallel stream");
787
+ }
788
+ return Stream.of(this.internalIterator()).flatten();
789
+ }
790
+ [Symbol.asyncIterator]() {
791
+ return this.isParallel ? this.join() : this;
792
+ }
793
+ next(...args) {
794
+ if (this.concurrencyLimit || this.sourceStream) {
795
+ throw new IllegalOperationError.IllegalOperationError("Iterator cannot be called on a parallel stream.Please join first");
796
+ }
797
+ return this.internalNext().run();
798
+ }
799
+ return(value) {
800
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
801
+ if (this.concurrencyLimit || this.sourceStream) {
802
+ throw new IllegalOperationError.IllegalOperationError("Iterator cannot be called on a parallel stream.Please join first");
803
+ }
804
+ return { done: true, value: yield this.execute().run() };
805
+ });
806
+ }
807
+ throw(e) {
808
+ return _tslib.__awaiter(this, void 0, void 0, function* () {
809
+ return {
810
+ done: true,
811
+ value: undefined,
812
+ };
813
+ });
814
+ }
815
+ __execute__(preProcessor = R__namespace.identity) {
816
+ return future.Future.of((resolve, __, signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
817
+ this.executed = true;
818
+ let i = 0;
819
+ let traversableActions = this.actions;
820
+ let data;
821
+ try {
822
+ const { index: actionStream, data: actionData } = yield this.checkBacklog(signal);
823
+ if (actionStream >= 0) {
824
+ i = actionStream;
825
+ data = actionData;
826
+ }
827
+ else if (this.canRunExecutor) {
828
+ do {
829
+ data = this.executor(this.controller.signal);
830
+ do {
831
+ if (data instanceof stream_state.ExecutorState) {
832
+ this.canRunExecutor = !data.done;
833
+ data = data.value;
834
+ if (!this.canRunExecutor && (data === null || data === undefined)) {
835
+ [data, traversableActions] = yield this.findAndExecuteMostRecentPacker(signal);
836
+ if (data === undefined) {
837
+ return resolve({ state: exports.State.DONE });
838
+ }
839
+ }
840
+ }
841
+ if (data instanceof Promise)
842
+ data = yield data;
843
+ if (data instanceof future.Future)
844
+ data = yield data.registerSignal(signal);
845
+ if (data instanceof result.FutureResult)
846
+ data = data.value;
847
+ if (data instanceof Stream) {
848
+ this.backlog.push({ actionStream: 0, records: data });
849
+ return resolve({ state: exports.State.CONTINUE });
850
+ }
851
+ } while (data instanceof stream_state.ExecutorState);
852
+ } while (data === undefined && this.canRunExecutor);
853
+ }
854
+ else {
855
+ [data, traversableActions] = yield this.findAndExecuteMostRecentPacker(signal);
856
+ if (data === undefined) {
857
+ return resolve({ state: exports.State.DONE });
858
+ }
859
+ }
860
+ }
861
+ catch (e) {
862
+ const [value, index] = yield this.processError(e, i, traversableActions, signal);
863
+ i = index + 1;
864
+ if (value === undefined || value === null)
865
+ return resolve({ state: exports.State.CONTINUE });
866
+ data = value;
867
+ }
868
+ resolve(yield this.processor(i, traversableActions, data, preProcessor, signal));
869
+ }), this.controller.signal);
870
+ }
871
+ processor(index, traversableActions, record, preProcessor = R__namespace.identity, signal) {
872
+ return future.Future.of((resolve, reject, signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
873
+ let data = record;
874
+ for (let i = index; i < traversableActions.length; i++) {
875
+ try {
876
+ const { type, functor } = traversableActions[i];
877
+ switch (type) {
878
+ case ActionType.FILTER: {
879
+ const preResult = yield this.yieldTrueResult(preProcessor(data), signal);
880
+ const result = yield this.yieldTrueResult(functor(preResult instanceof Promise ? yield preResult : preResult), signal);
881
+ if (result === null || result === undefined) {
882
+ return resolve({ state: exports.State.CONTINUE });
883
+ }
884
+ data = result;
885
+ break;
886
+ }
887
+ case ActionType.TRANSFORM: {
888
+ const preResult = yield this.yieldTrueResult(preProcessor(data), signal);
889
+ const result = yield this.yieldTrueResult(functor(preResult instanceof Promise ? yield preResult : preResult), signal);
890
+ if (result instanceof Stream) {
891
+ this.backlog = [{ actionStream: i + 1, records: result }, ...this.backlog];
892
+ return resolve({ state: exports.State.CONTINUE });
893
+ }
894
+ data = result;
895
+ break;
896
+ }
897
+ case ActionType.PACK: {
898
+ const preResult = yield this.yieldTrueResult(preProcessor(data), signal);
899
+ const result = (yield this.yieldTrueResult(functor(preResult instanceof Promise ? yield preResult : preResult), signal));
900
+ if (!result.done) {
901
+ return resolve({ state: exports.State.CONTINUE });
902
+ }
903
+ data = result.value;
904
+ break;
905
+ }
906
+ case ActionType.LIMIT: {
907
+ const preResult = yield this.yieldTrueResult(preProcessor(data), signal);
908
+ const result = (yield this.yieldTrueResult(functor(preResult instanceof Promise ? yield preResult : preResult), signal));
909
+ if (result.done) {
910
+ this.canRunExecutor = false;
911
+ this.backlog = [];
912
+ this.actions = traversableActions.splice(i + 1);
913
+ traversableActions = this.actions;
914
+ i = -1;
915
+ }
916
+ data = result.value;
917
+ break;
918
+ }
919
+ case ActionType.UNPACK: {
920
+ const preResult = yield this.yieldTrueResult(preProcessor(data), signal);
921
+ const result = (yield this.yieldTrueResult(functor(preResult instanceof Promise ? yield preResult : preResult), signal));
922
+ if (result.length === 0) {
923
+ return resolve({ state: exports.State.CONTINUE });
924
+ }
925
+ else if (result.length === 1) {
926
+ data = result[0];
927
+ }
928
+ else {
929
+ const value = result.shift();
930
+ this.backlog = [{ actionStream: i + 1, records: result }, ...this.backlog];
931
+ data = value;
932
+ }
933
+ }
934
+ }
935
+ }
936
+ catch (error) {
937
+ const [value, index] = yield this.processError(error, i, traversableActions, signal);
938
+ i = index;
939
+ if (value !== undefined && value !== null)
940
+ data = value;
941
+ }
942
+ }
943
+ return resolve({ state: exports.State.MATCHED, value: data });
944
+ }), signal);
945
+ }
946
+ internalIterator() {
947
+ const iterator = {
948
+ next: () => this.internalNext().run(),
949
+ return: this.return.bind(this),
950
+ throw: this.throw,
951
+ [Symbol.asyncIterator]() {
952
+ return iterator;
953
+ },
954
+ };
955
+ return iterator;
956
+ }
957
+ checkBacklog(signal) {
958
+ return future.Future.of((resolve, __, signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
959
+ if (this.backlog.length === 0)
960
+ return resolve({ index: -1 });
961
+ const { actionStream, records } = this.backlog[0];
962
+ const index = actionStream;
963
+ if (records instanceof Stream) {
964
+ const hook = () => records.cancel();
965
+ this.onCancellation(hook);
966
+ try {
967
+ const { value: data, done } = yield records[Symbol.asyncIterator]().next();
968
+ if (done) {
969
+ this.backlog.shift();
970
+ return resolve(yield this.checkBacklog(signal));
971
+ }
972
+ return resolve({ index, data });
973
+ }
974
+ finally {
975
+ this.removeCancelHook(hook);
976
+ }
977
+ }
978
+ else {
979
+ const data = records.shift();
980
+ if (records.length === 0) {
981
+ this.backlog.shift();
982
+ }
983
+ return resolve({ index, data });
984
+ }
985
+ }), signal);
986
+ }
987
+ internalNext() {
988
+ return this.runLock.with(({ signal }) => _tslib.__awaiter(this, void 0, void 0, function* () {
989
+ try {
990
+ while (!this.done) {
991
+ const { state, value } = yield (this.sourceStream && this.concurrencyLimit
992
+ ? this.forwardExecute()
993
+ : this.__execute__());
994
+ if (state === exports.State.MATCHED && value !== undefined)
995
+ return { done: false, value };
996
+ if (state === exports.State.DONE) {
997
+ this.done = true;
998
+ if (value !== undefined)
999
+ return { done: false, value };
1000
+ }
1001
+ if (this.controller.signal.aborted) {
1002
+ this.done = true;
1003
+ }
1004
+ }
1005
+ this.invokeCompletionHooks();
1006
+ return { done: true, value: undefined };
1007
+ }
1008
+ catch (error) {
1009
+ this.invokeCompletionHooks();
1010
+ if (error instanceof StreamEnded.StreamEnded || error instanceof FutureCancelled.FutureCancelled)
1011
+ return { done: true, value: null };
1012
+ throw error;
1013
+ }
1014
+ }));
1015
+ }
1016
+ invokeCompletionHooks() {
1017
+ if (this.completionHookInvoked) {
1018
+ return;
1019
+ }
1020
+ this.completionHookInvoked = true;
1021
+ this.completionHooks.forEach((handler) => {
1022
+ void new Promise((resolve, reject) => {
1023
+ try {
1024
+ handler();
1025
+ resolve(null);
1026
+ }
1027
+ catch (e) {
1028
+ reject(e);
1029
+ }
1030
+ });
1031
+ });
1032
+ this.backlog.forEach(({ records }) => {
1033
+ if (records instanceof Stream) {
1034
+ records.cancel();
1035
+ }
1036
+ });
1037
+ }
1038
+ processError(error, i, actions, signal) {
1039
+ return future.Future.of((resolve, reject, signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
1040
+ let errorMessage;
1041
+ if (actions.length === 0)
1042
+ throw error;
1043
+ else if (!(error instanceof Error))
1044
+ errorMessage = new Error(error);
1045
+ else
1046
+ errorMessage = error;
1047
+ const catchAction = actions.splice(i).find((v, index) => {
1048
+ if (v.type === ActionType.CATCH) {
1049
+ i = index;
1050
+ return true;
1051
+ }
1052
+ return false;
1053
+ });
1054
+ if (!catchAction)
1055
+ throw error;
1056
+ try {
1057
+ const value = catchAction.functor(errorMessage);
1058
+ return resolve([yield this.yieldTrueResult(value, signal), i]);
1059
+ }
1060
+ catch (e) {
1061
+ return resolve(yield this.processError(e, i, actions, signal));
1062
+ }
1063
+ }), signal);
1064
+ }
1065
+ findAndExecuteMostRecentPacker(signal) {
1066
+ return future.Future.of((resolve, __, signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
1067
+ const index = this.actions.findIndex((action) => action.type === ActionType.PACK);
1068
+ if (index >= 0) {
1069
+ const functor = this.actions[index].functor;
1070
+ const result = (yield this.yieldTrueResult(functor(undefined), signal));
1071
+ if (result.done) {
1072
+ return resolve([result.value, this.actions.slice(index + 1)]);
1073
+ }
1074
+ }
1075
+ return resolve([undefined, []]);
1076
+ }), signal);
1077
+ }
1078
+ yieldTrueResult(value, signal) {
1079
+ return future.Future.of((resolve, reject, signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
1080
+ if (value instanceof future.Future)
1081
+ value = yield value.registerSignal(signal);
1082
+ if (value instanceof result.FutureResult)
1083
+ value = value.value;
1084
+ if (value instanceof Promise)
1085
+ value = yield value;
1086
+ resolve(value);
1087
+ }), signal);
1088
+ }
1089
+ forwardExecute(preProcessor = R__namespace.identity) {
1090
+ return future.Future.of((resolve, reject, signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
1091
+ var _a, e_4, _b, _c;
1092
+ let pending = [];
1093
+ try {
1094
+ for (var _d = true, _e = _tslib.__asyncValues(this.sourceStream.internalIterator()), _f; _f = yield _e.next(), _a = _f.done, !_a;) {
1095
+ _c = _f.value;
1096
+ _d = false;
1097
+ try {
1098
+ const data = _c;
1099
+ pending.push(this.processor(0, this.actions, data, preProcessor, signal));
1100
+ if (pending.length === this.concurrencyLimit) {
1101
+ const result = yield this.collectResult(pending, signal);
1102
+ if (result.state === exports.State.CONTINUE) {
1103
+ pending = [];
1104
+ }
1105
+ else {
1106
+ return resolve(result);
1107
+ }
1108
+ }
1109
+ }
1110
+ finally {
1111
+ _d = true;
1112
+ }
1113
+ }
1114
+ }
1115
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
1116
+ finally {
1117
+ try {
1118
+ if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
1119
+ }
1120
+ finally { if (e_4) throw e_4.error; }
1121
+ }
1122
+ const { state, value } = yield this.collectResult(pending, signal);
1123
+ if (state === exports.State.CONTINUE) {
1124
+ return resolve({ state: exports.State.DONE });
1125
+ }
1126
+ return resolve({ state: exports.State.DONE, value });
1127
+ }));
1128
+ }
1129
+ collectResult(pending, signal) {
1130
+ return future.Future.of((resolve, reject, signal) => _tslib.__awaiter(this, void 0, void 0, function* () {
1131
+ let doneFound = false;
1132
+ const results = (yield future.Future.collect(pending).registerSignal(signal)).filter((v) => {
1133
+ if (v.state === exports.State.DONE) {
1134
+ doneFound = true;
1135
+ return true;
1136
+ }
1137
+ else if (v.state === exports.State.MATCHED) {
1138
+ return true;
1139
+ }
1140
+ return false;
1141
+ });
1142
+ if (doneFound) {
1143
+ return resolve({ state: exports.State.DONE, value: results.map((v) => v.value) });
1144
+ }
1145
+ else if (results.length) {
1146
+ return resolve({ state: exports.State.MATCHED, value: results.map((v) => v.value) });
1147
+ }
1148
+ return resolve({ state: exports.State.CONTINUE });
1149
+ }), signal);
1150
+ }
1151
+ }
1152
+
1153
+ exports.Stream = Stream;