@nlozgachev/pipelined 0.19.0 → 0.21.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.
@@ -0,0 +1,1398 @@
1
+ import {
2
+ Deferred,
3
+ Maybe,
4
+ Result,
5
+ Task
6
+ } from "./chunk-2DPG2RDB.mjs";
7
+
8
+ // src/Core/Lens.ts
9
+ var Lens;
10
+ ((Lens2) => {
11
+ Lens2.make = (get2, set2) => ({ get: get2, set: set2 });
12
+ Lens2.prop = () => (key) => (0, Lens2.make)(
13
+ (s) => s[key],
14
+ (a) => (s) => ({ ...s, [key]: a })
15
+ );
16
+ Lens2.get = (lens) => (s) => lens.get(s);
17
+ Lens2.set = (lens) => (a) => (s) => lens.set(a)(s);
18
+ Lens2.modify = (lens) => (f) => (s) => lens.set(f(lens.get(s)))(s);
19
+ Lens2.andThen = (inner) => (outer) => (0, Lens2.make)(
20
+ (s) => inner.get(outer.get(s)),
21
+ (b) => (s) => outer.set(inner.set(b)(outer.get(s)))(s)
22
+ );
23
+ Lens2.andThenOptional = (inner) => (outer) => ({
24
+ get: (s) => inner.get(outer.get(s)),
25
+ set: (b) => (s) => outer.set(inner.set(b)(outer.get(s)))(s)
26
+ });
27
+ Lens2.toOptional = (lens) => ({
28
+ get: (s) => ({ kind: "Some", value: lens.get(s) }),
29
+ set: lens.set
30
+ });
31
+ })(Lens || (Lens = {}));
32
+
33
+ // src/Core/Logged.ts
34
+ var Logged;
35
+ ((Logged2) => {
36
+ Logged2.make = (value) => ({ value, log: [] });
37
+ Logged2.tell = (entry) => ({ value: void 0, log: [entry] });
38
+ Logged2.map = (f) => (data) => ({
39
+ value: f(data.value),
40
+ log: data.log
41
+ });
42
+ Logged2.chain = (f) => (data) => {
43
+ const next = f(data.value);
44
+ return { value: next.value, log: [...data.log, ...next.log] };
45
+ };
46
+ Logged2.ap = (arg) => (data) => ({
47
+ value: data.value(arg.value),
48
+ log: [...data.log, ...arg.log]
49
+ });
50
+ Logged2.tap = (f) => (data) => {
51
+ f(data.value);
52
+ return data;
53
+ };
54
+ Logged2.run = (data) => [data.value, data.log];
55
+ })(Logged || (Logged = {}));
56
+
57
+ // src/internal/Op.util.ts
58
+ var _abortedNil = { kind: "Nil", reason: "aborted" };
59
+ var _droppedNil = { kind: "Nil", reason: "dropped" };
60
+ var _replacedNil = { kind: "Nil", reason: "replaced" };
61
+ var _evictedNil = { kind: "Nil", reason: "evicted" };
62
+ var _idle = { kind: "Idle" };
63
+ var _pending = { kind: "Pending" };
64
+ var ok = (value) => ({ kind: "Ok", value });
65
+ var err = (error) => ({ kind: "Err", error });
66
+ var cancellableWait = (ms, signal) => {
67
+ if (ms <= 0) return Promise.resolve();
68
+ return new Promise((resolve) => {
69
+ const id = setTimeout(resolve, ms);
70
+ signal.addEventListener("abort", () => {
71
+ clearTimeout(id);
72
+ resolve();
73
+ }, { once: true });
74
+ });
75
+ };
76
+ var runWithRetry = (op, input, signal, options, onRetrying) => {
77
+ const { attempts, backoff, when: shouldRetry } = options;
78
+ const getDelay = (n) => backoff === void 0 ? 0 : typeof backoff === "function" ? backoff(n) : backoff;
79
+ const attempt = async (left) => {
80
+ const result = await Deferred.toPromise(op._factory(input, signal));
81
+ if (result === null || signal.aborted) return null;
82
+ if (result.kind === "Ok") return result;
83
+ if (left <= 1) return result;
84
+ if (shouldRetry !== void 0 && !shouldRetry(result.error)) return result;
85
+ const attemptNumber = attempts - left + 1;
86
+ const ms = getDelay(attemptNumber);
87
+ onRetrying({
88
+ kind: "Retrying",
89
+ attempt: attemptNumber,
90
+ lastError: result.error,
91
+ ...ms > 0 ? { nextRetryIn: ms } : {}
92
+ });
93
+ await cancellableWait(ms, signal);
94
+ if (signal.aborted) return null;
95
+ return attempt(left - 1);
96
+ };
97
+ return attempt(attempts);
98
+ };
99
+ var execute = (op, input, controller, retryOptions, timeoutOptions, onRetrying) => {
100
+ const { signal } = controller;
101
+ const toOutcome = (r) => r === null ? _abortedNil : r.kind === "Ok" ? ok(r.value) : err(r.error);
102
+ const runPromise = retryOptions !== void 0 && onRetrying !== void 0 ? runWithRetry(op, input, signal, retryOptions, onRetrying).then(toOutcome) : Deferred.toPromise(op._factory(input, signal)).then(toOutcome);
103
+ if (timeoutOptions === void 0) return Deferred.fromPromise(runPromise);
104
+ let timerId;
105
+ return Deferred.fromPromise(Promise.race([
106
+ runPromise.then((outcome) => {
107
+ clearTimeout(timerId);
108
+ return outcome;
109
+ }),
110
+ new Promise((resolve) => {
111
+ timerId = setTimeout(() => {
112
+ controller.abort();
113
+ resolve(err(timeoutOptions.onTimeout()));
114
+ }, timeoutOptions.ms);
115
+ })
116
+ ]));
117
+ };
118
+ var makeRestartable = (op, minInterval, retryOptions, timeoutOptions) => {
119
+ let currentState = _idle;
120
+ let currentController;
121
+ let currentResolve;
122
+ let waitController;
123
+ let lastStartTime = 0;
124
+ const subscribers = /* @__PURE__ */ new Set();
125
+ const emit = (state) => {
126
+ currentState = state;
127
+ subscribers.forEach((cb) => cb(state));
128
+ };
129
+ const run = (input) => Deferred.fromPromise(
130
+ new Promise((resolve) => {
131
+ waitController?.abort();
132
+ waitController = void 0;
133
+ currentController?.abort();
134
+ const prev = currentResolve;
135
+ currentResolve = resolve;
136
+ currentController = new AbortController();
137
+ const controller = currentController;
138
+ prev?.(_replacedNil);
139
+ const startExecution = () => {
140
+ if (currentController !== controller) return;
141
+ lastStartTime = Date.now();
142
+ emit(_pending);
143
+ const onRetrying = retryOptions ? (r) => {
144
+ if (currentController === controller) emit(r);
145
+ } : void 0;
146
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
147
+ if (currentController !== controller) return;
148
+ const r = currentResolve;
149
+ currentResolve = void 0;
150
+ currentController = void 0;
151
+ emit(outcome);
152
+ r?.(outcome);
153
+ });
154
+ };
155
+ const gap = minInterval !== void 0 ? Math.max(0, minInterval - (Date.now() - lastStartTime)) : 0;
156
+ if (gap > 0) {
157
+ waitController = new AbortController();
158
+ const wc = waitController;
159
+ cancellableWait(gap, wc.signal).then(() => {
160
+ if (waitController === wc) waitController = void 0;
161
+ startExecution();
162
+ });
163
+ } else {
164
+ startExecution();
165
+ }
166
+ })
167
+ );
168
+ const abort = () => {
169
+ waitController?.abort();
170
+ waitController = void 0;
171
+ currentController?.abort();
172
+ currentController = void 0;
173
+ const r = currentResolve;
174
+ currentResolve = void 0;
175
+ if (currentState.kind !== "Idle") emit(_abortedNil);
176
+ r?.(_abortedNil);
177
+ };
178
+ return {
179
+ get state() {
180
+ return currentState;
181
+ },
182
+ run,
183
+ abort,
184
+ subscribe: (cb) => {
185
+ subscribers.add(cb);
186
+ if (currentState.kind !== "Idle") cb(currentState);
187
+ return () => subscribers.delete(cb);
188
+ }
189
+ };
190
+ };
191
+ var makeExclusive = (op, cooldown, retryOptions, timeoutOptions) => {
192
+ let currentState = _idle;
193
+ let currentController;
194
+ let currentResolve;
195
+ let cooldownTimer;
196
+ const subscribers = /* @__PURE__ */ new Set();
197
+ const emit = (state) => {
198
+ currentState = state;
199
+ subscribers.forEach((cb) => cb(state));
200
+ };
201
+ const run = (input) => {
202
+ if (currentController !== void 0 || cooldownTimer !== void 0) {
203
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
204
+ }
205
+ return Deferred.fromPromise(
206
+ new Promise((resolve) => {
207
+ currentResolve = resolve;
208
+ currentController = new AbortController();
209
+ const controller = currentController;
210
+ emit(_pending);
211
+ const onRetrying = retryOptions ? (r) => {
212
+ if (currentController === controller) emit(r);
213
+ } : void 0;
214
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
215
+ if (currentController !== controller) return;
216
+ const r = currentResolve;
217
+ currentResolve = void 0;
218
+ currentController = void 0;
219
+ emit(outcome);
220
+ r?.(outcome);
221
+ if (cooldown !== void 0 && cooldown > 0) {
222
+ cooldownTimer = setTimeout(() => {
223
+ cooldownTimer = void 0;
224
+ }, cooldown);
225
+ }
226
+ });
227
+ })
228
+ );
229
+ };
230
+ const abort = () => {
231
+ if (cooldownTimer !== void 0) {
232
+ clearTimeout(cooldownTimer);
233
+ cooldownTimer = void 0;
234
+ }
235
+ currentController?.abort();
236
+ currentController = void 0;
237
+ const r = currentResolve;
238
+ currentResolve = void 0;
239
+ if (currentState.kind !== "Idle") emit(_abortedNil);
240
+ r?.(_abortedNil);
241
+ };
242
+ return {
243
+ get state() {
244
+ return currentState;
245
+ },
246
+ run,
247
+ abort,
248
+ subscribe: (cb) => {
249
+ subscribers.add(cb);
250
+ if (currentState.kind !== "Idle") cb(currentState);
251
+ return () => subscribers.delete(cb);
252
+ }
253
+ };
254
+ };
255
+ var makeQueue = (op, maxSize, overflow, concurrency, dedupe, retryOptions, timeoutOptions) => {
256
+ const maxConcurrency = concurrency ?? 1;
257
+ let currentState = _idle;
258
+ let generation = 0;
259
+ let inFlight = 0;
260
+ const queue = [];
261
+ const inflightControllers = /* @__PURE__ */ new Set();
262
+ const inflightResolvers = [];
263
+ const subscribers = /* @__PURE__ */ new Set();
264
+ const emit = (state) => {
265
+ currentState = state;
266
+ subscribers.forEach((cb) => cb(state));
267
+ };
268
+ const startOne = (input, resolve, myGeneration) => {
269
+ inFlight++;
270
+ const controller = new AbortController();
271
+ inflightControllers.add(controller);
272
+ inflightResolvers.push(resolve);
273
+ emit(_pending);
274
+ const onRetrying = retryOptions ? (r) => {
275
+ if (generation === myGeneration && inflightControllers.has(controller)) emit(r);
276
+ } : void 0;
277
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
278
+ inflightControllers.delete(controller);
279
+ const idx = inflightResolvers.indexOf(resolve);
280
+ if (idx !== -1) inflightResolvers.splice(idx, 1);
281
+ if (generation !== myGeneration) {
282
+ resolve(_abortedNil);
283
+ return;
284
+ }
285
+ inFlight--;
286
+ emit(outcome);
287
+ resolve(outcome);
288
+ if (queue.length > 0) {
289
+ const next = queue.shift();
290
+ startOne(next.input, next.resolve, generation);
291
+ }
292
+ });
293
+ };
294
+ const run = (input) => {
295
+ const myGeneration = generation;
296
+ if (dedupe !== void 0) {
297
+ const idx = queue.findIndex((item) => dedupe(input, item.input));
298
+ if (idx !== -1) {
299
+ const dup = queue.splice(idx, 1)[0];
300
+ dup.resolve(_droppedNil);
301
+ }
302
+ }
303
+ if (inFlight < maxConcurrency) {
304
+ return Deferred.fromPromise(
305
+ new Promise((resolve) => {
306
+ startOne(input, resolve, myGeneration);
307
+ })
308
+ );
309
+ }
310
+ if (maxSize === void 0 || queue.length < maxSize) {
311
+ return Deferred.fromPromise(
312
+ new Promise((resolve) => {
313
+ queue.push({ input, resolve });
314
+ emit({ kind: "Queued", position: queue.length - 1 });
315
+ })
316
+ );
317
+ }
318
+ if (overflow === "replace-last") {
319
+ return Deferred.fromPromise(
320
+ new Promise((resolve) => {
321
+ const tail = queue.pop();
322
+ tail.resolve(_evictedNil);
323
+ queue.push({ input, resolve });
324
+ emit({ kind: "Queued", position: queue.length - 1 });
325
+ })
326
+ );
327
+ }
328
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
329
+ };
330
+ const abort = () => {
331
+ generation++;
332
+ inflightControllers.forEach((c) => c.abort());
333
+ inflightControllers.clear();
334
+ const toResolve = inflightResolvers.splice(0);
335
+ const queuedResolvers = queue.splice(0).map((item) => item.resolve);
336
+ inFlight = 0;
337
+ if (currentState.kind !== "Idle") emit(_abortedNil);
338
+ toResolve.forEach((r) => r(_abortedNil));
339
+ queuedResolvers.forEach((r) => r(_abortedNil));
340
+ };
341
+ return {
342
+ get state() {
343
+ return currentState;
344
+ },
345
+ run,
346
+ abort,
347
+ subscribe: (cb) => {
348
+ subscribers.add(cb);
349
+ if (currentState.kind !== "Idle") cb(currentState);
350
+ return () => subscribers.delete(cb);
351
+ }
352
+ };
353
+ };
354
+ var makeBuffered = (op, size, retryOptions, timeoutOptions) => {
355
+ const bufferSize = size ?? 1;
356
+ let currentState = _idle;
357
+ let currentController;
358
+ let currentResolve;
359
+ const buffer = [];
360
+ const subscribers = /* @__PURE__ */ new Set();
361
+ const emit = (state) => {
362
+ currentState = state;
363
+ subscribers.forEach((cb) => cb(state));
364
+ };
365
+ const startRun = (input, resolve) => {
366
+ currentResolve = resolve;
367
+ currentController = new AbortController();
368
+ const controller = currentController;
369
+ emit(_pending);
370
+ const onRetrying = retryOptions ? (r) => {
371
+ if (currentController === controller) emit(r);
372
+ } : void 0;
373
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
374
+ if (currentController !== controller) return;
375
+ const r = currentResolve;
376
+ currentResolve = void 0;
377
+ currentController = void 0;
378
+ emit(outcome);
379
+ r?.(outcome);
380
+ if (buffer.length > 0) {
381
+ const next = buffer.shift();
382
+ startRun(next.input, next.resolve);
383
+ }
384
+ });
385
+ };
386
+ const run = (input) => Deferred.fromPromise(
387
+ new Promise((resolve) => {
388
+ if (currentController === void 0) {
389
+ startRun(input, resolve);
390
+ } else if (buffer.length < bufferSize) {
391
+ buffer.push({ input, resolve });
392
+ emit({ kind: "Queued", position: buffer.length - 1 });
393
+ } else {
394
+ const evicted = buffer.shift();
395
+ evicted.resolve(_evictedNil);
396
+ buffer.push({ input, resolve });
397
+ emit({ kind: "Queued", position: buffer.length - 1 });
398
+ }
399
+ })
400
+ );
401
+ const abort = () => {
402
+ currentController?.abort();
403
+ currentController = void 0;
404
+ const cr = currentResolve;
405
+ currentResolve = void 0;
406
+ const bufferedResolvers = buffer.splice(0).map((item) => item.resolve);
407
+ if (currentState.kind !== "Idle") emit(_abortedNil);
408
+ cr?.(_abortedNil);
409
+ bufferedResolvers.forEach((r) => r(_abortedNil));
410
+ };
411
+ return {
412
+ get state() {
413
+ return currentState;
414
+ },
415
+ run,
416
+ abort,
417
+ subscribe: (cb) => {
418
+ subscribers.add(cb);
419
+ if (currentState.kind !== "Idle") cb(currentState);
420
+ return () => subscribers.delete(cb);
421
+ }
422
+ };
423
+ };
424
+ var makeDebounced = (op, ms, leading, maxWait, retryOptions, timeoutOptions) => {
425
+ let currentState = _idle;
426
+ let currentController;
427
+ let currentResolve;
428
+ let leadingController;
429
+ let leadingResolve;
430
+ let pendingResolve;
431
+ let timerId;
432
+ let pendingInput;
433
+ let firstCallAt = 0;
434
+ const subscribers = /* @__PURE__ */ new Set();
435
+ const emit = (state) => {
436
+ currentState = state;
437
+ subscribers.forEach((cb) => cb(state));
438
+ };
439
+ const fireLeading = (input, resolve) => {
440
+ leadingController = new AbortController();
441
+ const controller = leadingController;
442
+ leadingResolve = resolve;
443
+ emit(_pending);
444
+ const onRetrying = retryOptions ? (r) => {
445
+ if (leadingController === controller) emit(r);
446
+ } : void 0;
447
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
448
+ if (leadingController !== controller) return;
449
+ const r = leadingResolve;
450
+ leadingResolve = void 0;
451
+ leadingController = void 0;
452
+ emit(outcome);
453
+ r?.(outcome);
454
+ });
455
+ };
456
+ const fireTrailing = () => {
457
+ timerId = void 0;
458
+ firstCallAt = 0;
459
+ const capturedResolve = pendingResolve;
460
+ pendingResolve = void 0;
461
+ if (capturedResolve === void 0) return;
462
+ currentResolve = capturedResolve;
463
+ const toRun = pendingInput;
464
+ pendingInput = void 0;
465
+ currentController = new AbortController();
466
+ const controller = currentController;
467
+ emit(_pending);
468
+ const onRetrying = retryOptions ? (r) => {
469
+ if (currentController === controller) emit(r);
470
+ } : void 0;
471
+ execute(op, toRun, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
472
+ if (currentController !== controller) return;
473
+ const r = currentResolve;
474
+ currentResolve = void 0;
475
+ currentController = void 0;
476
+ emit(outcome);
477
+ r?.(outcome);
478
+ });
479
+ };
480
+ const scheduleTrailing = () => {
481
+ if (timerId !== void 0) clearTimeout(timerId);
482
+ let delay = ms;
483
+ if (maxWait !== void 0 && firstCallAt > 0) {
484
+ const maxDelay = firstCallAt + maxWait - Date.now();
485
+ delay = Math.min(ms, Math.max(0, maxDelay));
486
+ }
487
+ timerId = setTimeout(fireTrailing, delay);
488
+ };
489
+ const inDebounceWindow = () => timerId !== void 0 || leadingController !== void 0 || currentController !== void 0;
490
+ const run = (input) => Deferred.fromPromise(
491
+ new Promise((resolve) => {
492
+ if (!inDebounceWindow()) {
493
+ firstCallAt = Date.now();
494
+ if (leading) {
495
+ fireLeading(input, resolve);
496
+ scheduleTrailing();
497
+ } else {
498
+ pendingInput = input;
499
+ pendingResolve = resolve;
500
+ scheduleTrailing();
501
+ }
502
+ } else {
503
+ const prev = pendingResolve;
504
+ pendingInput = input;
505
+ pendingResolve = resolve;
506
+ prev?.(_evictedNil);
507
+ scheduleTrailing();
508
+ }
509
+ })
510
+ );
511
+ const abort = () => {
512
+ if (timerId !== void 0) {
513
+ clearTimeout(timerId);
514
+ timerId = void 0;
515
+ pendingInput = void 0;
516
+ firstCallAt = 0;
517
+ }
518
+ const pr = pendingResolve;
519
+ pendingResolve = void 0;
520
+ const cr = currentResolve;
521
+ currentResolve = void 0;
522
+ currentController?.abort();
523
+ currentController = void 0;
524
+ const lr = leadingResolve;
525
+ leadingResolve = void 0;
526
+ leadingController?.abort();
527
+ leadingController = void 0;
528
+ if (currentState.kind !== "Idle") emit(_abortedNil);
529
+ pr?.(_abortedNil);
530
+ cr?.(_abortedNil);
531
+ lr?.(_abortedNil);
532
+ };
533
+ return {
534
+ get state() {
535
+ return currentState;
536
+ },
537
+ run,
538
+ abort,
539
+ subscribe: (cb) => {
540
+ subscribers.add(cb);
541
+ if (currentState.kind !== "Idle") cb(currentState);
542
+ return () => subscribers.delete(cb);
543
+ }
544
+ };
545
+ };
546
+ var makeThrottled = (op, ms, trailing, retryOptions, timeoutOptions) => {
547
+ let currentState = _idle;
548
+ let currentController;
549
+ let currentResolve;
550
+ let cooldownTimer;
551
+ let pendingInput;
552
+ let pendingResolve;
553
+ const subscribers = /* @__PURE__ */ new Set();
554
+ const emit = (state) => {
555
+ currentState = state;
556
+ subscribers.forEach((cb) => cb(state));
557
+ };
558
+ const fireOp = (input, resolve) => {
559
+ currentResolve = resolve;
560
+ currentController = new AbortController();
561
+ const controller = currentController;
562
+ emit(_pending);
563
+ const onRetrying = retryOptions ? (r) => {
564
+ if (currentController === controller) emit(r);
565
+ } : void 0;
566
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
567
+ if (currentController !== controller) return;
568
+ const r = currentResolve;
569
+ currentResolve = void 0;
570
+ currentController = void 0;
571
+ emit(outcome);
572
+ r?.(outcome);
573
+ });
574
+ };
575
+ const startCooldown = () => {
576
+ cooldownTimer = setTimeout(() => {
577
+ cooldownTimer = void 0;
578
+ if (trailing && pendingInput !== void 0) {
579
+ const input = pendingInput;
580
+ const resolve = pendingResolve;
581
+ pendingInput = void 0;
582
+ pendingResolve = void 0;
583
+ fireOp(input, resolve);
584
+ startCooldown();
585
+ }
586
+ }, ms);
587
+ };
588
+ const run = (input) => {
589
+ if (cooldownTimer !== void 0) {
590
+ if (!trailing) {
591
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
592
+ }
593
+ return Deferred.fromPromise(
594
+ new Promise((resolve) => {
595
+ const prev = pendingResolve;
596
+ pendingInput = input;
597
+ pendingResolve = resolve;
598
+ prev?.(_evictedNil);
599
+ })
600
+ );
601
+ }
602
+ return Deferred.fromPromise(
603
+ new Promise((resolve) => {
604
+ fireOp(input, resolve);
605
+ startCooldown();
606
+ })
607
+ );
608
+ };
609
+ const abort = () => {
610
+ if (cooldownTimer !== void 0) {
611
+ clearTimeout(cooldownTimer);
612
+ cooldownTimer = void 0;
613
+ }
614
+ currentController?.abort();
615
+ currentController = void 0;
616
+ const cr = currentResolve;
617
+ currentResolve = void 0;
618
+ const pr = pendingResolve;
619
+ pendingResolve = void 0;
620
+ pendingInput = void 0;
621
+ if (currentState.kind !== "Idle") emit(_abortedNil);
622
+ cr?.(_abortedNil);
623
+ pr?.(_abortedNil);
624
+ };
625
+ return {
626
+ get state() {
627
+ return currentState;
628
+ },
629
+ run,
630
+ abort,
631
+ subscribe: (cb) => {
632
+ subscribers.add(cb);
633
+ if (currentState.kind !== "Idle") cb(currentState);
634
+ return () => subscribers.delete(cb);
635
+ }
636
+ };
637
+ };
638
+ var makeConcurrent = (op, n, overflow, retryOptions, timeoutOptions) => {
639
+ let currentState = _idle;
640
+ let inflight = 0;
641
+ let generation = 0;
642
+ const controllers = /* @__PURE__ */ new Set();
643
+ const inflightResolvers = [];
644
+ const overflowQueue = [];
645
+ const subscribers = /* @__PURE__ */ new Set();
646
+ const emit = (state) => {
647
+ currentState = state;
648
+ subscribers.forEach((cb) => cb(state));
649
+ };
650
+ const startOne = (input, resolve, myGeneration) => {
651
+ inflight++;
652
+ const controller = new AbortController();
653
+ controllers.add(controller);
654
+ inflightResolvers.push(resolve);
655
+ emit(_pending);
656
+ const onRetrying = retryOptions ? (r) => {
657
+ if (generation === myGeneration && controllers.has(controller)) emit(r);
658
+ } : void 0;
659
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
660
+ controllers.delete(controller);
661
+ const idx = inflightResolvers.indexOf(resolve);
662
+ if (idx !== -1) inflightResolvers.splice(idx, 1);
663
+ if (generation !== myGeneration) {
664
+ resolve(_abortedNil);
665
+ return;
666
+ }
667
+ inflight--;
668
+ emit(outcome);
669
+ resolve(outcome);
670
+ if (overflowQueue.length > 0) {
671
+ const next = overflowQueue.shift();
672
+ startOne(next.input, next.resolve, generation);
673
+ }
674
+ });
675
+ };
676
+ const run = (input) => {
677
+ const myGeneration = generation;
678
+ if (inflight < n) {
679
+ return Deferred.fromPromise(
680
+ new Promise((resolve) => {
681
+ startOne(input, resolve, myGeneration);
682
+ })
683
+ );
684
+ }
685
+ if (overflow === "drop") {
686
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
687
+ }
688
+ return Deferred.fromPromise(
689
+ new Promise((resolve) => {
690
+ overflowQueue.push({ input, resolve });
691
+ emit({ kind: "Queued", position: overflowQueue.length - 1 });
692
+ })
693
+ );
694
+ };
695
+ const abort = () => {
696
+ generation++;
697
+ controllers.forEach((c) => c.abort());
698
+ controllers.clear();
699
+ const toResolve = inflightResolvers.splice(0);
700
+ const queuedResolvers = overflowQueue.splice(0).map((item) => item.resolve);
701
+ inflight = 0;
702
+ if (currentState.kind !== "Idle") emit(_abortedNil);
703
+ toResolve.forEach((r) => r(_abortedNil));
704
+ queuedResolvers.forEach((r) => r(_abortedNil));
705
+ };
706
+ return {
707
+ get state() {
708
+ return currentState;
709
+ },
710
+ run,
711
+ abort,
712
+ subscribe: (cb) => {
713
+ subscribers.add(cb);
714
+ if (currentState.kind !== "Idle") cb(currentState);
715
+ return () => subscribers.delete(cb);
716
+ }
717
+ };
718
+ };
719
+ var makeKeyed = (op, keyFn, perKey, timeoutOptions) => {
720
+ const stateMap = /* @__PURE__ */ new Map();
721
+ const slots = /* @__PURE__ */ new Map();
722
+ const subscribers = /* @__PURE__ */ new Set();
723
+ const emitSnapshot = () => {
724
+ const snapshot = new Map(stateMap);
725
+ subscribers.forEach((cb) => cb(snapshot));
726
+ };
727
+ const run = (input) => {
728
+ const k = keyFn(input);
729
+ if (slots.has(k)) {
730
+ if (perKey === "exclusive") {
731
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
732
+ }
733
+ const existing = slots.get(k);
734
+ existing.controller.abort();
735
+ const prev = existing.resolve;
736
+ slots.delete(k);
737
+ prev(_replacedNil);
738
+ }
739
+ return Deferred.fromPromise(
740
+ new Promise((resolve) => {
741
+ const controller = new AbortController();
742
+ slots.set(k, { controller, resolve });
743
+ stateMap.set(k, _pending);
744
+ emitSnapshot();
745
+ execute(op, input, controller, void 0, timeoutOptions, void 0).then((outcome) => {
746
+ const slot = slots.get(k);
747
+ if (!slot || slot.controller !== controller) {
748
+ resolve(_abortedNil);
749
+ return;
750
+ }
751
+ slots.delete(k);
752
+ stateMap.set(k, outcome);
753
+ emitSnapshot();
754
+ resolve(outcome);
755
+ });
756
+ })
757
+ );
758
+ };
759
+ const abort = (key) => {
760
+ if (key !== void 0) {
761
+ const slot = slots.get(key);
762
+ if (slot) {
763
+ slot.controller.abort();
764
+ const r = slot.resolve;
765
+ slots.delete(key);
766
+ stateMap.set(key, _abortedNil);
767
+ emitSnapshot();
768
+ r(_abortedNil);
769
+ }
770
+ } else {
771
+ const toResolve = [];
772
+ for (const [k, slot] of slots) {
773
+ slot.controller.abort();
774
+ toResolve.push(slot.resolve);
775
+ stateMap.set(k, _abortedNil);
776
+ }
777
+ slots.clear();
778
+ if (toResolve.length > 0) emitSnapshot();
779
+ toResolve.forEach((r) => r(_abortedNil));
780
+ }
781
+ };
782
+ return {
783
+ get state() {
784
+ return new Map(stateMap);
785
+ },
786
+ run,
787
+ abort,
788
+ subscribe: (cb) => {
789
+ subscribers.add(cb);
790
+ if (stateMap.size > 0) cb(new Map(stateMap));
791
+ return () => subscribers.delete(cb);
792
+ }
793
+ };
794
+ };
795
+ var makeOnce = (op, retryOptions, timeoutOptions) => {
796
+ let currentState = _idle;
797
+ let currentController;
798
+ let currentResolve;
799
+ const subscribers = /* @__PURE__ */ new Set();
800
+ const emit = (state) => {
801
+ currentState = state;
802
+ subscribers.forEach((cb) => cb(state));
803
+ };
804
+ const run = (input) => {
805
+ if (currentState.kind !== "Idle") {
806
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
807
+ }
808
+ return Deferred.fromPromise(
809
+ new Promise((resolve) => {
810
+ currentResolve = resolve;
811
+ currentController = new AbortController();
812
+ const controller = currentController;
813
+ emit(_pending);
814
+ const onRetrying = retryOptions ? (r) => {
815
+ if (currentController === controller) emit(r);
816
+ } : void 0;
817
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
818
+ if (currentController !== controller) return;
819
+ const r = currentResolve;
820
+ currentResolve = void 0;
821
+ currentController = void 0;
822
+ emit(outcome);
823
+ r?.(outcome);
824
+ });
825
+ })
826
+ );
827
+ };
828
+ const abort = () => {
829
+ currentController?.abort();
830
+ currentController = void 0;
831
+ const r = currentResolve;
832
+ currentResolve = void 0;
833
+ if (currentState.kind !== "Idle") emit(_abortedNil);
834
+ r?.(_abortedNil);
835
+ };
836
+ return {
837
+ get state() {
838
+ return currentState;
839
+ },
840
+ run,
841
+ abort,
842
+ subscribe: (cb) => {
843
+ subscribers.add(cb);
844
+ if (currentState.kind !== "Idle") cb(currentState);
845
+ return () => subscribers.delete(cb);
846
+ }
847
+ };
848
+ };
849
+
850
+ // src/Core/Op.ts
851
+ var Op;
852
+ ((Op2) => {
853
+ Op2.nil = (reason) => ({ kind: "Nil", reason });
854
+ Op2.create = (factory, onError) => ({
855
+ _factory: (input, signal) => Deferred.fromPromise(
856
+ factory(input, signal).then((value) => Result.ok(value)).catch((e) => signal.aborted ? null : Result.err(onError(e)))
857
+ )
858
+ });
859
+ Op2.ok = (value) => ({ kind: "Ok", value });
860
+ Op2.err = (error) => ({ kind: "Err", error });
861
+ Op2.isOk = (outcome) => outcome.kind === "Ok";
862
+ Op2.isErr = (outcome) => outcome.kind === "Err";
863
+ Op2.isNil = (outcome) => outcome.kind === "Nil";
864
+ Op2.match = (cases) => (outcome) => {
865
+ if (outcome.kind === "Ok") return cases.ok(outcome.value);
866
+ if (outcome.kind === "Err") return cases.err(outcome.error);
867
+ return cases.nil();
868
+ };
869
+ Op2.fold = (onErr, onOk, onNil) => (outcome) => {
870
+ if (outcome.kind === "Ok") return onOk(outcome.value);
871
+ if (outcome.kind === "Err") return onErr(outcome.error);
872
+ return onNil();
873
+ };
874
+ Op2.getOrElse = (defaultValue) => (outcome) => outcome.kind === "Ok" ? outcome.value : defaultValue();
875
+ Op2.map = (f) => (outcome) => outcome.kind === "Ok" ? (0, Op2.ok)(f(outcome.value)) : outcome;
876
+ Op2.mapError = (f) => (outcome) => outcome.kind === "Err" ? (0, Op2.err)(f(outcome.error)) : outcome;
877
+ Op2.chain = (f) => (outcome) => outcome.kind === "Ok" ? f(outcome.value) : outcome;
878
+ Op2.tap = (f) => (outcome) => {
879
+ if (outcome.kind === "Ok") f(outcome.value);
880
+ return outcome;
881
+ };
882
+ Op2.recover = (f) => (outcome) => outcome.kind === "Err" ? f(outcome.error) : outcome;
883
+ Op2.toResult = (onNil) => (outcome) => {
884
+ if (outcome.kind === "Ok") return Result.ok(outcome.value);
885
+ if (outcome.kind === "Err") return Result.err(outcome.error);
886
+ return Result.err(onNil());
887
+ };
888
+ Op2.toMaybe = (outcome) => outcome.kind === "Ok" ? Maybe.some(outcome.value) : Maybe.none();
889
+ Op2.all = (invocations) => Deferred.fromPromise(Promise.all(invocations.map(Deferred.toPromise)));
890
+ Op2.race = (invocations) => Deferred.fromPromise(Promise.race(invocations.map(Deferred.toPromise)));
891
+ function interpret(op, options) {
892
+ const { strategy, retry: retryOptions, timeout: timeoutOptions } = options;
893
+ switch (strategy) {
894
+ case "once":
895
+ return makeOnce(op, retryOptions, timeoutOptions);
896
+ case "restartable":
897
+ return makeRestartable(op, options.minInterval, retryOptions, timeoutOptions);
898
+ case "exclusive":
899
+ return makeExclusive(op, options.cooldown, retryOptions, timeoutOptions);
900
+ case "queue":
901
+ return makeQueue(
902
+ op,
903
+ options.maxSize,
904
+ options.overflow,
905
+ options.concurrency,
906
+ options.dedupe,
907
+ retryOptions,
908
+ timeoutOptions
909
+ );
910
+ case "buffered":
911
+ return makeBuffered(op, options.size, retryOptions, timeoutOptions);
912
+ case "debounced":
913
+ return makeDebounced(op, options.ms ?? 0, options.leading ?? false, options.maxWait, retryOptions, timeoutOptions);
914
+ case "throttled":
915
+ return makeThrottled(op, options.ms ?? 0, options.trailing ?? false, retryOptions, timeoutOptions);
916
+ case "concurrent":
917
+ return makeConcurrent(
918
+ op,
919
+ options.n ?? 1,
920
+ options.overflow ?? "drop",
921
+ retryOptions,
922
+ timeoutOptions
923
+ );
924
+ case "keyed":
925
+ return makeKeyed(op, options.key ?? ((i) => i), options.perKey ?? "exclusive", timeoutOptions);
926
+ }
927
+ }
928
+ Op2.interpret = interpret;
929
+ })(Op || (Op = {}));
930
+
931
+ // src/Core/Optional.ts
932
+ var Optional;
933
+ ((Optional2) => {
934
+ Optional2.make = (get2, set2) => ({ get: get2, set: set2 });
935
+ Optional2.prop = () => (key) => (0, Optional2.make)(
936
+ (s) => {
937
+ const val = s[key];
938
+ return val !== null && val !== void 0 ? Maybe.some(val) : Maybe.none();
939
+ },
940
+ (a) => (s) => ({ ...s, [key]: a })
941
+ );
942
+ Optional2.index = (i) => (0, Optional2.make)(
943
+ (arr) => i >= 0 && i < arr.length ? Maybe.some(arr[i]) : Maybe.none(),
944
+ (a) => (arr) => {
945
+ if (i < 0 || i >= arr.length) return arr;
946
+ const copy = [...arr];
947
+ copy[i] = a;
948
+ return copy;
949
+ }
950
+ );
951
+ Optional2.get = (opt) => (s) => opt.get(s);
952
+ Optional2.set = (opt) => (a) => (s) => opt.set(a)(s);
953
+ Optional2.modify = (opt) => (f) => (s) => {
954
+ const val = opt.get(s);
955
+ return val.kind === "None" ? s : opt.set(f(val.value))(s);
956
+ };
957
+ Optional2.getOrElse = (opt) => (defaultValue) => (s) => {
958
+ const val = opt.get(s);
959
+ return val.kind === "Some" ? val.value : defaultValue();
960
+ };
961
+ Optional2.fold = (opt) => (onNone, onSome) => (s) => {
962
+ const val = opt.get(s);
963
+ return val.kind === "Some" ? onSome(val.value) : onNone();
964
+ };
965
+ Optional2.match = (opt) => (cases) => (s) => {
966
+ const val = opt.get(s);
967
+ return val.kind === "Some" ? cases.some(val.value) : cases.none();
968
+ };
969
+ Optional2.andThen = (inner) => (outer) => (0, Optional2.make)(
970
+ (s) => {
971
+ const mid = outer.get(s);
972
+ return mid.kind === "None" ? Maybe.none() : inner.get(mid.value);
973
+ },
974
+ (b) => (s) => {
975
+ const mid = outer.get(s);
976
+ return mid.kind === "None" ? s : outer.set(inner.set(b)(mid.value))(s);
977
+ }
978
+ );
979
+ Optional2.andThenLens = (inner) => (outer) => (0, Optional2.make)(
980
+ (s) => {
981
+ const mid = outer.get(s);
982
+ return mid.kind === "None" ? Maybe.none() : Maybe.some(inner.get(mid.value));
983
+ },
984
+ (b) => (s) => {
985
+ const mid = outer.get(s);
986
+ return mid.kind === "None" ? s : outer.set(inner.set(b)(mid.value))(s);
987
+ }
988
+ );
989
+ })(Optional || (Optional = {}));
990
+
991
+ // src/Core/Predicate.ts
992
+ var Predicate;
993
+ ((Predicate2) => {
994
+ Predicate2.not = (p) => (a) => !p(a);
995
+ Predicate2.and = (second) => (first) => (a) => first(a) && second(a);
996
+ Predicate2.or = (second) => (first) => (a) => first(a) || second(a);
997
+ Predicate2.using = (f) => (p) => (b) => p(f(b));
998
+ Predicate2.all = (predicates) => (a) => predicates.every((p) => p(a));
999
+ Predicate2.any = (predicates) => (a) => predicates.some((p) => p(a));
1000
+ Predicate2.fromRefinement = (r) => r;
1001
+ })(Predicate || (Predicate = {}));
1002
+
1003
+ // src/Core/Reader.ts
1004
+ var Reader;
1005
+ ((Reader2) => {
1006
+ Reader2.resolve = (value) => (_env) => value;
1007
+ Reader2.ask = () => (env) => env;
1008
+ Reader2.asks = (f) => (env) => f(env);
1009
+ Reader2.map = (f) => (data) => (env) => f(data(env));
1010
+ Reader2.chain = (f) => (data) => (env) => f(data(env))(env);
1011
+ Reader2.ap = (arg) => (data) => (env) => data(env)(arg(env));
1012
+ Reader2.tap = (f) => (data) => (env) => {
1013
+ const a = data(env);
1014
+ f(a);
1015
+ return a;
1016
+ };
1017
+ Reader2.local = (f) => (data) => (env) => data(f(env));
1018
+ Reader2.run = (env) => (data) => data(env);
1019
+ })(Reader || (Reader = {}));
1020
+
1021
+ // src/Core/Refinement.ts
1022
+ var Refinement;
1023
+ ((Refinement2) => {
1024
+ Refinement2.make = (f) => f;
1025
+ Refinement2.compose = (bc) => (ab) => (a) => ab(a) && bc(a);
1026
+ Refinement2.and = (second) => (first) => (a) => first(a) && second(a);
1027
+ Refinement2.or = (second) => (first) => (a) => first(a) || second(a);
1028
+ Refinement2.toFilter = (r) => (a) => r(a) ? Maybe.some(a) : Maybe.none();
1029
+ Refinement2.toResult = (r, onFail) => (a) => r(a) ? Result.ok(a) : Result.err(onFail(a));
1030
+ })(Refinement || (Refinement = {}));
1031
+
1032
+ // src/Core/RemoteData.ts
1033
+ var _notAsked = { kind: "NotAsked" };
1034
+ var _loading = { kind: "Loading" };
1035
+ var RemoteData;
1036
+ ((RemoteData2) => {
1037
+ RemoteData2.notAsked = () => _notAsked;
1038
+ RemoteData2.loading = () => _loading;
1039
+ RemoteData2.failure = (error) => ({
1040
+ kind: "Failure",
1041
+ error
1042
+ });
1043
+ RemoteData2.success = (value) => ({
1044
+ kind: "Success",
1045
+ value
1046
+ });
1047
+ RemoteData2.isNotAsked = (data) => data.kind === "NotAsked";
1048
+ RemoteData2.isLoading = (data) => data.kind === "Loading";
1049
+ RemoteData2.isFailure = (data) => data.kind === "Failure";
1050
+ RemoteData2.isSuccess = (data) => data.kind === "Success";
1051
+ RemoteData2.map = (f) => (data) => (0, RemoteData2.isSuccess)(data) ? (0, RemoteData2.success)(f(data.value)) : data;
1052
+ RemoteData2.mapError = (f) => (data) => (0, RemoteData2.isFailure)(data) ? (0, RemoteData2.failure)(f(data.error)) : data;
1053
+ RemoteData2.chain = (f) => (data) => (0, RemoteData2.isSuccess)(data) ? f(data.value) : data;
1054
+ RemoteData2.ap = (arg) => (data) => {
1055
+ if ((0, RemoteData2.isSuccess)(data) && (0, RemoteData2.isSuccess)(arg)) {
1056
+ return (0, RemoteData2.success)(data.value(arg.value));
1057
+ }
1058
+ if ((0, RemoteData2.isFailure)(data)) return data;
1059
+ if ((0, RemoteData2.isFailure)(arg)) return arg;
1060
+ if ((0, RemoteData2.isLoading)(data) || (0, RemoteData2.isLoading)(arg)) return (0, RemoteData2.loading)();
1061
+ return (0, RemoteData2.notAsked)();
1062
+ };
1063
+ RemoteData2.fold = (onNotAsked, onLoading, onFailure, onSuccess) => (data) => {
1064
+ switch (data.kind) {
1065
+ case "NotAsked":
1066
+ return onNotAsked();
1067
+ case "Loading":
1068
+ return onLoading();
1069
+ case "Failure":
1070
+ return onFailure(data.error);
1071
+ case "Success":
1072
+ return onSuccess(data.value);
1073
+ }
1074
+ };
1075
+ RemoteData2.match = (cases) => (data) => {
1076
+ switch (data.kind) {
1077
+ case "NotAsked":
1078
+ return cases.notAsked();
1079
+ case "Loading":
1080
+ return cases.loading();
1081
+ case "Failure":
1082
+ return cases.failure(data.error);
1083
+ case "Success":
1084
+ return cases.success(data.value);
1085
+ }
1086
+ };
1087
+ RemoteData2.getOrElse = (defaultValue) => (data) => (0, RemoteData2.isSuccess)(data) ? data.value : defaultValue();
1088
+ RemoteData2.tap = (f) => (data) => {
1089
+ if ((0, RemoteData2.isSuccess)(data)) f(data.value);
1090
+ return data;
1091
+ };
1092
+ RemoteData2.recover = (fallback) => (data) => (0, RemoteData2.isFailure)(data) ? fallback(data.error) : data;
1093
+ RemoteData2.toMaybe = (data) => (0, RemoteData2.isSuccess)(data) ? Maybe.some(data.value) : Maybe.none();
1094
+ RemoteData2.toResult = (onNotReady) => (data) => (0, RemoteData2.isSuccess)(data) ? Result.ok(data.value) : Result.err((0, RemoteData2.isFailure)(data) ? data.error : onNotReady());
1095
+ })(RemoteData || (RemoteData = {}));
1096
+
1097
+ // src/Core/Resource.ts
1098
+ var Resource;
1099
+ ((Resource2) => {
1100
+ Resource2.make = (acquire, release) => ({ acquire, release });
1101
+ Resource2.fromTask = (acquire, release) => ({
1102
+ acquire: Task.map((a) => Result.ok(a))(acquire),
1103
+ release
1104
+ });
1105
+ Resource2.use = (f) => (resource) => Task.from(
1106
+ () => Deferred.toPromise(resource.acquire()).then(async (acquired) => {
1107
+ if (Result.isErr(acquired)) return acquired;
1108
+ const a = acquired.value;
1109
+ const usageResult = await Deferred.toPromise(f(a)());
1110
+ await Deferred.toPromise(resource.release(a)());
1111
+ return usageResult;
1112
+ })
1113
+ );
1114
+ Resource2.combine = (resourceA, resourceB) => ({
1115
+ acquire: Task.from(
1116
+ () => Deferred.toPromise(resourceA.acquire()).then(async (acquiredA) => {
1117
+ if (Result.isErr(acquiredA)) return acquiredA;
1118
+ const a = acquiredA.value;
1119
+ const acquiredB = await Deferred.toPromise(resourceB.acquire());
1120
+ if (Result.isErr(acquiredB)) {
1121
+ await Deferred.toPromise(resourceA.release(a)());
1122
+ return acquiredB;
1123
+ }
1124
+ return Result.ok([a, acquiredB.value]);
1125
+ })
1126
+ ),
1127
+ release: ([a, b]) => Task.from(() => Deferred.toPromise(resourceB.release(b)()).then(() => Deferred.toPromise(resourceA.release(a)())))
1128
+ });
1129
+ })(Resource || (Resource = {}));
1130
+
1131
+ // src/Core/State.ts
1132
+ var State;
1133
+ ((State2) => {
1134
+ State2.resolve = (value) => (s) => [value, s];
1135
+ State2.get = () => (s) => [s, s];
1136
+ State2.gets = (f) => (s) => [f(s), s];
1137
+ State2.put = (newState) => (_s) => [void 0, newState];
1138
+ State2.modify = (f) => (s) => [void 0, f(s)];
1139
+ State2.map = (f) => (st) => (s) => {
1140
+ const [a, s1] = st(s);
1141
+ return [f(a), s1];
1142
+ };
1143
+ State2.chain = (f) => (st) => (s) => {
1144
+ const [a, s1] = st(s);
1145
+ return f(a)(s1);
1146
+ };
1147
+ State2.ap = (arg) => (fn) => (s) => {
1148
+ const [f, s1] = fn(s);
1149
+ const [a, s2] = arg(s1);
1150
+ return [f(a), s2];
1151
+ };
1152
+ State2.tap = (f) => (st) => (s) => {
1153
+ const [a, s1] = st(s);
1154
+ f(a);
1155
+ return [a, s1];
1156
+ };
1157
+ State2.run = (initialState) => (st) => st(initialState);
1158
+ State2.evaluate = (initialState) => (st) => st(initialState)[0];
1159
+ State2.execute = (initialState) => (st) => st(initialState)[1];
1160
+ })(State || (State = {}));
1161
+
1162
+ // src/Core/TaskMaybe.ts
1163
+ var TaskMaybe;
1164
+ ((TaskMaybe2) => {
1165
+ TaskMaybe2.some = (value) => Task.resolve(Maybe.some(value));
1166
+ TaskMaybe2.none = () => Task.resolve(Maybe.none());
1167
+ TaskMaybe2.fromMaybe = (option) => Task.resolve(option);
1168
+ TaskMaybe2.fromTask = (task) => Task.map(Maybe.some)(task);
1169
+ TaskMaybe2.tryCatch = (f) => Task.from(
1170
+ () => f().then(Maybe.some).catch(() => Maybe.none())
1171
+ );
1172
+ TaskMaybe2.map = (f) => (data) => Task.map(Maybe.map(f))(data);
1173
+ TaskMaybe2.chain = (f) => (data) => Task.chain((option) => Maybe.isSome(option) ? f(option.value) : Task.resolve(Maybe.none()))(data);
1174
+ TaskMaybe2.ap = (arg) => (data) => Task.from(
1175
+ () => Promise.all([
1176
+ Deferred.toPromise(data()),
1177
+ Deferred.toPromise(arg())
1178
+ ]).then(([of_, oa]) => Maybe.ap(oa)(of_))
1179
+ );
1180
+ TaskMaybe2.fold = (onNone, onSome) => (data) => Task.map(Maybe.fold(onNone, onSome))(data);
1181
+ TaskMaybe2.match = (cases) => (data) => Task.map(Maybe.match(cases))(data);
1182
+ TaskMaybe2.getOrElse = (defaultValue) => (data) => Task.map(Maybe.getOrElse(defaultValue))(data);
1183
+ TaskMaybe2.tap = (f) => (data) => Task.map(Maybe.tap(f))(data);
1184
+ TaskMaybe2.filter = (predicate) => (data) => Task.map(Maybe.filter(predicate))(data);
1185
+ TaskMaybe2.toTaskResult = (onNone) => (data) => Task.map(Maybe.toResult(onNone))(data);
1186
+ })(TaskMaybe || (TaskMaybe = {}));
1187
+
1188
+ // src/Core/TaskResult.ts
1189
+ var TaskResult;
1190
+ ((TaskResult2) => {
1191
+ TaskResult2.ok = (value) => Task.resolve(Result.ok(value));
1192
+ TaskResult2.err = (error) => Task.resolve(Result.err(error));
1193
+ TaskResult2.tryCatch = (f, onError) => Task.from(
1194
+ (signal) => f(signal).then(Result.ok).catch((e) => Result.err(onError(e)))
1195
+ );
1196
+ TaskResult2.map = (f) => (data) => Task.map(Result.map(f))(data);
1197
+ TaskResult2.mapError = (f) => (data) => Task.map(Result.mapError(f))(data);
1198
+ TaskResult2.chain = (f) => (data) => Task.chain((result) => Result.isOk(result) ? f(result.value) : Task.resolve(Result.err(result.error)))(
1199
+ data
1200
+ );
1201
+ TaskResult2.fold = (onErr, onOk) => (data) => Task.map(Result.fold(onErr, onOk))(data);
1202
+ TaskResult2.match = (cases) => (data) => Task.map(Result.match(cases))(data);
1203
+ TaskResult2.recover = (fallback) => (data) => Task.chain(
1204
+ (result) => Result.isErr(result) ? fallback(result.error) : Task.resolve(result)
1205
+ )(data);
1206
+ TaskResult2.getOrElse = (defaultValue) => (data) => Task.map(Result.getOrElse(defaultValue))(data);
1207
+ TaskResult2.tap = (f) => (data) => Task.map(Result.tap(f))(data);
1208
+ })(TaskResult || (TaskResult = {}));
1209
+
1210
+ // src/Core/Validation.ts
1211
+ var Validation;
1212
+ ((Validation2) => {
1213
+ Validation2.valid = (value) => ({
1214
+ kind: "Valid",
1215
+ value
1216
+ });
1217
+ Validation2.invalid = (error) => ({
1218
+ kind: "Invalid",
1219
+ errors: [error]
1220
+ });
1221
+ Validation2.invalidAll = (errors) => ({
1222
+ kind: "Invalid",
1223
+ errors
1224
+ });
1225
+ Validation2.isValid = (data) => data.kind === "Valid";
1226
+ Validation2.isInvalid = (data) => data.kind === "Invalid";
1227
+ Validation2.map = (f) => (data) => (0, Validation2.isValid)(data) ? (0, Validation2.valid)(f(data.value)) : data;
1228
+ Validation2.ap = (arg) => (data) => {
1229
+ if ((0, Validation2.isValid)(data) && (0, Validation2.isValid)(arg)) return (0, Validation2.valid)(data.value(arg.value));
1230
+ const errors = [
1231
+ ...(0, Validation2.isInvalid)(data) ? data.errors : [],
1232
+ ...(0, Validation2.isInvalid)(arg) ? arg.errors : []
1233
+ ];
1234
+ return (0, Validation2.invalidAll)(errors);
1235
+ };
1236
+ Validation2.fold = (onInvalid, onValid) => (data) => (0, Validation2.isValid)(data) ? onValid(data.value) : onInvalid(data.errors);
1237
+ Validation2.match = (cases) => (data) => (0, Validation2.isValid)(data) ? cases.valid(data.value) : cases.invalid(data.errors);
1238
+ Validation2.getOrElse = (defaultValue) => (data) => (0, Validation2.isValid)(data) ? data.value : defaultValue();
1239
+ Validation2.tap = (f) => (data) => {
1240
+ if ((0, Validation2.isValid)(data)) f(data.value);
1241
+ return data;
1242
+ };
1243
+ Validation2.recover = (fallback) => (data) => (0, Validation2.isValid)(data) ? data : fallback(data.errors);
1244
+ Validation2.recoverUnless = (blockedErrors, fallback) => (data) => (0, Validation2.isInvalid)(data) && !data.errors.some((err2) => blockedErrors.includes(err2)) ? fallback() : data;
1245
+ Validation2.product = (first, second) => {
1246
+ if ((0, Validation2.isValid)(first) && (0, Validation2.isValid)(second)) return (0, Validation2.valid)([first.value, second.value]);
1247
+ const errors = [
1248
+ ...(0, Validation2.isInvalid)(first) ? first.errors : [],
1249
+ ...(0, Validation2.isInvalid)(second) ? second.errors : []
1250
+ ];
1251
+ return (0, Validation2.invalidAll)(errors);
1252
+ };
1253
+ Validation2.productAll = (data) => {
1254
+ const values = [];
1255
+ const errors = [];
1256
+ for (const v of data) {
1257
+ if ((0, Validation2.isValid)(v)) values.push(v.value);
1258
+ else errors.push(...v.errors);
1259
+ }
1260
+ return errors.length > 0 ? (0, Validation2.invalidAll)(errors) : (0, Validation2.valid)(values);
1261
+ };
1262
+ })(Validation || (Validation = {}));
1263
+
1264
+ // src/Core/TaskValidation.ts
1265
+ var TaskValidation;
1266
+ ((TaskValidation2) => {
1267
+ TaskValidation2.valid = (value) => Task.resolve(Validation.valid(value));
1268
+ TaskValidation2.invalid = (error) => Task.resolve(Validation.invalid(error));
1269
+ TaskValidation2.invalidAll = (errors) => Task.resolve(Validation.invalidAll(errors));
1270
+ TaskValidation2.fromValidation = (validation) => Task.resolve(validation);
1271
+ TaskValidation2.tryCatch = (f, onError) => Task.from(
1272
+ () => f().then(Validation.valid).catch((e) => Validation.invalid(onError(e)))
1273
+ );
1274
+ TaskValidation2.map = (f) => (data) => Task.map(Validation.map(f))(data);
1275
+ TaskValidation2.ap = (arg) => (data) => Task.from(
1276
+ () => Promise.all([
1277
+ Deferred.toPromise(data()),
1278
+ Deferred.toPromise(arg())
1279
+ ]).then(([vf, va]) => Validation.ap(va)(vf))
1280
+ );
1281
+ TaskValidation2.fold = (onInvalid, onValid) => (data) => Task.map(Validation.fold(onInvalid, onValid))(data);
1282
+ TaskValidation2.match = (cases) => (data) => Task.map(Validation.match(cases))(data);
1283
+ TaskValidation2.getOrElse = (defaultValue) => (data) => Task.map(Validation.getOrElse(defaultValue))(data);
1284
+ TaskValidation2.tap = (f) => (data) => Task.map(Validation.tap(f))(data);
1285
+ TaskValidation2.recover = (fallback) => (data) => Task.chain(
1286
+ (validation) => Validation.isValid(validation) ? Task.resolve(validation) : fallback(validation.errors)
1287
+ )(data);
1288
+ TaskValidation2.product = (first, second) => Task.from(
1289
+ () => Promise.all([
1290
+ Deferred.toPromise(first()),
1291
+ Deferred.toPromise(second())
1292
+ ]).then(([va, vb]) => Validation.product(va, vb))
1293
+ );
1294
+ TaskValidation2.productAll = (data) => Task.from(
1295
+ () => Promise.all(data.map((t) => Deferred.toPromise(t()))).then((results) => Validation.productAll(results))
1296
+ );
1297
+ })(TaskValidation || (TaskValidation = {}));
1298
+
1299
+ // src/Core/These.ts
1300
+ var These;
1301
+ ((These2) => {
1302
+ These2.first = (value) => ({ kind: "First", first: value });
1303
+ These2.second = (value) => ({ kind: "Second", second: value });
1304
+ These2.both = (first2, second2) => ({
1305
+ kind: "Both",
1306
+ first: first2,
1307
+ second: second2
1308
+ });
1309
+ These2.isFirst = (data) => data.kind === "First";
1310
+ These2.isSecond = (data) => data.kind === "Second";
1311
+ These2.isBoth = (data) => data.kind === "Both";
1312
+ These2.hasFirst = (data) => data.kind === "First" || data.kind === "Both";
1313
+ These2.hasSecond = (data) => data.kind === "Second" || data.kind === "Both";
1314
+ These2.mapFirst = (f) => (data) => {
1315
+ if ((0, These2.isSecond)(data)) return data;
1316
+ if ((0, These2.isFirst)(data)) return (0, These2.first)(f(data.first));
1317
+ return (0, These2.both)(f(data.first), data.second);
1318
+ };
1319
+ These2.mapSecond = (f) => (data) => {
1320
+ if ((0, These2.isFirst)(data)) return data;
1321
+ if ((0, These2.isSecond)(data)) return (0, These2.second)(f(data.second));
1322
+ return (0, These2.both)(data.first, f(data.second));
1323
+ };
1324
+ These2.mapBoth = (onFirst, onSecond) => (data) => {
1325
+ if ((0, These2.isSecond)(data)) return (0, These2.second)(onSecond(data.second));
1326
+ if ((0, These2.isFirst)(data)) return (0, These2.first)(onFirst(data.first));
1327
+ return (0, These2.both)(onFirst(data.first), onSecond(data.second));
1328
+ };
1329
+ These2.chainFirst = (f) => (data) => {
1330
+ if ((0, These2.isSecond)(data)) return data;
1331
+ return f(data.first);
1332
+ };
1333
+ These2.chainSecond = (f) => (data) => {
1334
+ if ((0, These2.isFirst)(data)) return data;
1335
+ return f(data.second);
1336
+ };
1337
+ These2.fold = (onFirst, onSecond, onBoth) => (data) => {
1338
+ if ((0, These2.isSecond)(data)) return onSecond(data.second);
1339
+ if ((0, These2.isFirst)(data)) return onFirst(data.first);
1340
+ return onBoth(data.first, data.second);
1341
+ };
1342
+ These2.match = (cases) => (data) => {
1343
+ if ((0, These2.isSecond)(data)) return cases.second(data.second);
1344
+ if ((0, These2.isFirst)(data)) return cases.first(data.first);
1345
+ return cases.both(data.first, data.second);
1346
+ };
1347
+ These2.getFirstOrElse = (defaultValue) => (data) => (0, These2.hasFirst)(data) ? data.first : defaultValue();
1348
+ These2.getSecondOrElse = (defaultValue) => (data) => (0, These2.hasSecond)(data) ? data.second : defaultValue();
1349
+ These2.tap = (f) => (data) => {
1350
+ if ((0, These2.hasFirst)(data)) f(data.first);
1351
+ return data;
1352
+ };
1353
+ These2.swap = (data) => {
1354
+ if ((0, These2.isSecond)(data)) return (0, These2.first)(data.second);
1355
+ if ((0, These2.isFirst)(data)) return (0, These2.second)(data.first);
1356
+ return (0, These2.both)(data.second, data.first);
1357
+ };
1358
+ })(These || (These = {}));
1359
+
1360
+ // src/Core/Tuple.ts
1361
+ var Tuple;
1362
+ ((Tuple2) => {
1363
+ Tuple2.make = (first2, second2) => [first2, second2];
1364
+ Tuple2.first = (tuple) => tuple[0];
1365
+ Tuple2.second = (tuple) => tuple[1];
1366
+ Tuple2.mapFirst = (f) => (tuple) => [f(tuple[0]), tuple[1]];
1367
+ Tuple2.mapSecond = (f) => (tuple) => [tuple[0], f(tuple[1])];
1368
+ Tuple2.mapBoth = (onFirst, onSecond) => (tuple) => [
1369
+ onFirst(tuple[0]),
1370
+ onSecond(tuple[1])
1371
+ ];
1372
+ Tuple2.fold = (f) => (tuple) => f(tuple[0], tuple[1]);
1373
+ Tuple2.swap = (tuple) => [tuple[1], tuple[0]];
1374
+ Tuple2.toArray = (tuple) => [...tuple];
1375
+ Tuple2.tap = (f) => (tuple) => {
1376
+ f(tuple[0], tuple[1]);
1377
+ return tuple;
1378
+ };
1379
+ })(Tuple || (Tuple = {}));
1380
+
1381
+ export {
1382
+ Lens,
1383
+ Logged,
1384
+ Op,
1385
+ Optional,
1386
+ Predicate,
1387
+ Reader,
1388
+ Refinement,
1389
+ RemoteData,
1390
+ Resource,
1391
+ State,
1392
+ TaskMaybe,
1393
+ TaskResult,
1394
+ Validation,
1395
+ TaskValidation,
1396
+ These,
1397
+ Tuple
1398
+ };