@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.
package/dist/core.js CHANGED
@@ -24,6 +24,7 @@ __export(Core_exports, {
24
24
  Lens: () => Lens,
25
25
  Logged: () => Logged,
26
26
  Maybe: () => Maybe,
27
+ Op: () => Op,
27
28
  Optional: () => Optional,
28
29
  Predicate: () => Predicate,
29
30
  Reader: () => Reader,
@@ -43,15 +44,13 @@ __export(Core_exports, {
43
44
  module.exports = __toCommonJS(Core_exports);
44
45
 
45
46
  // src/Core/Deferred.ts
46
- var _store = /* @__PURE__ */ new WeakMap();
47
47
  var Deferred;
48
48
  ((Deferred2) => {
49
- Deferred2.fromPromise = (p) => {
50
- const d = { then: ((f) => p.then(f)) };
51
- _store.set(d, p);
52
- return d;
53
- };
54
- Deferred2.toPromise = (d) => _store.get(d) ?? new Promise((resolve) => d.then(resolve));
49
+ Deferred2.fromPromise = (p) => (
50
+ // eslint-disable-next-line unicorn/no-thenable -- Deferred is intentionally thenable; it is the mechanism that makes Task awaitable
51
+ { then: ((f) => p.then(f)) }
52
+ );
53
+ Deferred2.toPromise = (d) => new Promise((resolve) => d.then(resolve));
55
54
  })(Deferred || (Deferred = {}));
56
55
 
57
56
  // src/Core/Lens.ts
@@ -161,6 +160,880 @@ var Maybe;
161
160
  Maybe2.ap = (arg) => (data) => (0, Maybe2.isSome)(data) && (0, Maybe2.isSome)(arg) ? (0, Maybe2.some)(data.value(arg.value)) : (0, Maybe2.none)();
162
161
  })(Maybe || (Maybe = {}));
163
162
 
163
+ // src/internal/Op.util.ts
164
+ var _abortedNil = { kind: "Nil", reason: "aborted" };
165
+ var _droppedNil = { kind: "Nil", reason: "dropped" };
166
+ var _replacedNil = { kind: "Nil", reason: "replaced" };
167
+ var _evictedNil = { kind: "Nil", reason: "evicted" };
168
+ var _idle = { kind: "Idle" };
169
+ var _pending = { kind: "Pending" };
170
+ var ok = (value) => ({ kind: "Ok", value });
171
+ var err = (error) => ({ kind: "Err", error });
172
+ var cancellableWait = (ms, signal) => {
173
+ if (ms <= 0) return Promise.resolve();
174
+ return new Promise((resolve) => {
175
+ const id = setTimeout(resolve, ms);
176
+ signal.addEventListener("abort", () => {
177
+ clearTimeout(id);
178
+ resolve();
179
+ }, { once: true });
180
+ });
181
+ };
182
+ var runWithRetry = (op, input, signal, options, onRetrying) => {
183
+ const { attempts, backoff, when: shouldRetry } = options;
184
+ const getDelay = (n) => backoff === void 0 ? 0 : typeof backoff === "function" ? backoff(n) : backoff;
185
+ const attempt = async (left) => {
186
+ const result = await Deferred.toPromise(op._factory(input, signal));
187
+ if (result === null || signal.aborted) return null;
188
+ if (result.kind === "Ok") return result;
189
+ if (left <= 1) return result;
190
+ if (shouldRetry !== void 0 && !shouldRetry(result.error)) return result;
191
+ const attemptNumber = attempts - left + 1;
192
+ const ms = getDelay(attemptNumber);
193
+ onRetrying({
194
+ kind: "Retrying",
195
+ attempt: attemptNumber,
196
+ lastError: result.error,
197
+ ...ms > 0 ? { nextRetryIn: ms } : {}
198
+ });
199
+ await cancellableWait(ms, signal);
200
+ if (signal.aborted) return null;
201
+ return attempt(left - 1);
202
+ };
203
+ return attempt(attempts);
204
+ };
205
+ var execute = (op, input, controller, retryOptions, timeoutOptions, onRetrying) => {
206
+ const { signal } = controller;
207
+ const toOutcome = (r) => r === null ? _abortedNil : r.kind === "Ok" ? ok(r.value) : err(r.error);
208
+ const runPromise = retryOptions !== void 0 && onRetrying !== void 0 ? runWithRetry(op, input, signal, retryOptions, onRetrying).then(toOutcome) : Deferred.toPromise(op._factory(input, signal)).then(toOutcome);
209
+ if (timeoutOptions === void 0) return Deferred.fromPromise(runPromise);
210
+ let timerId;
211
+ return Deferred.fromPromise(Promise.race([
212
+ runPromise.then((outcome) => {
213
+ clearTimeout(timerId);
214
+ return outcome;
215
+ }),
216
+ new Promise((resolve) => {
217
+ timerId = setTimeout(() => {
218
+ controller.abort();
219
+ resolve(err(timeoutOptions.onTimeout()));
220
+ }, timeoutOptions.ms);
221
+ })
222
+ ]));
223
+ };
224
+ var makeRestartable = (op, minInterval, retryOptions, timeoutOptions) => {
225
+ let currentState = _idle;
226
+ let currentController;
227
+ let currentResolve;
228
+ let waitController;
229
+ let lastStartTime = 0;
230
+ const subscribers = /* @__PURE__ */ new Set();
231
+ const emit = (state) => {
232
+ currentState = state;
233
+ subscribers.forEach((cb) => cb(state));
234
+ };
235
+ const run = (input) => Deferred.fromPromise(
236
+ new Promise((resolve) => {
237
+ waitController?.abort();
238
+ waitController = void 0;
239
+ currentController?.abort();
240
+ const prev = currentResolve;
241
+ currentResolve = resolve;
242
+ currentController = new AbortController();
243
+ const controller = currentController;
244
+ prev?.(_replacedNil);
245
+ const startExecution = () => {
246
+ if (currentController !== controller) return;
247
+ lastStartTime = Date.now();
248
+ emit(_pending);
249
+ const onRetrying = retryOptions ? (r) => {
250
+ if (currentController === controller) emit(r);
251
+ } : void 0;
252
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
253
+ if (currentController !== controller) return;
254
+ const r = currentResolve;
255
+ currentResolve = void 0;
256
+ currentController = void 0;
257
+ emit(outcome);
258
+ r?.(outcome);
259
+ });
260
+ };
261
+ const gap = minInterval !== void 0 ? Math.max(0, minInterval - (Date.now() - lastStartTime)) : 0;
262
+ if (gap > 0) {
263
+ waitController = new AbortController();
264
+ const wc = waitController;
265
+ cancellableWait(gap, wc.signal).then(() => {
266
+ if (waitController === wc) waitController = void 0;
267
+ startExecution();
268
+ });
269
+ } else {
270
+ startExecution();
271
+ }
272
+ })
273
+ );
274
+ const abort = () => {
275
+ waitController?.abort();
276
+ waitController = void 0;
277
+ currentController?.abort();
278
+ currentController = void 0;
279
+ const r = currentResolve;
280
+ currentResolve = void 0;
281
+ if (currentState.kind !== "Idle") emit(_abortedNil);
282
+ r?.(_abortedNil);
283
+ };
284
+ return {
285
+ get state() {
286
+ return currentState;
287
+ },
288
+ run,
289
+ abort,
290
+ subscribe: (cb) => {
291
+ subscribers.add(cb);
292
+ if (currentState.kind !== "Idle") cb(currentState);
293
+ return () => subscribers.delete(cb);
294
+ }
295
+ };
296
+ };
297
+ var makeExclusive = (op, cooldown, retryOptions, timeoutOptions) => {
298
+ let currentState = _idle;
299
+ let currentController;
300
+ let currentResolve;
301
+ let cooldownTimer;
302
+ const subscribers = /* @__PURE__ */ new Set();
303
+ const emit = (state) => {
304
+ currentState = state;
305
+ subscribers.forEach((cb) => cb(state));
306
+ };
307
+ const run = (input) => {
308
+ if (currentController !== void 0 || cooldownTimer !== void 0) {
309
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
310
+ }
311
+ return Deferred.fromPromise(
312
+ new Promise((resolve) => {
313
+ currentResolve = resolve;
314
+ currentController = new AbortController();
315
+ const controller = currentController;
316
+ emit(_pending);
317
+ const onRetrying = retryOptions ? (r) => {
318
+ if (currentController === controller) emit(r);
319
+ } : void 0;
320
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
321
+ if (currentController !== controller) return;
322
+ const r = currentResolve;
323
+ currentResolve = void 0;
324
+ currentController = void 0;
325
+ emit(outcome);
326
+ r?.(outcome);
327
+ if (cooldown !== void 0 && cooldown > 0) {
328
+ cooldownTimer = setTimeout(() => {
329
+ cooldownTimer = void 0;
330
+ }, cooldown);
331
+ }
332
+ });
333
+ })
334
+ );
335
+ };
336
+ const abort = () => {
337
+ if (cooldownTimer !== void 0) {
338
+ clearTimeout(cooldownTimer);
339
+ cooldownTimer = void 0;
340
+ }
341
+ currentController?.abort();
342
+ currentController = void 0;
343
+ const r = currentResolve;
344
+ currentResolve = void 0;
345
+ if (currentState.kind !== "Idle") emit(_abortedNil);
346
+ r?.(_abortedNil);
347
+ };
348
+ return {
349
+ get state() {
350
+ return currentState;
351
+ },
352
+ run,
353
+ abort,
354
+ subscribe: (cb) => {
355
+ subscribers.add(cb);
356
+ if (currentState.kind !== "Idle") cb(currentState);
357
+ return () => subscribers.delete(cb);
358
+ }
359
+ };
360
+ };
361
+ var makeQueue = (op, maxSize, overflow, concurrency, dedupe, retryOptions, timeoutOptions) => {
362
+ const maxConcurrency = concurrency ?? 1;
363
+ let currentState = _idle;
364
+ let generation = 0;
365
+ let inFlight = 0;
366
+ const queue = [];
367
+ const inflightControllers = /* @__PURE__ */ new Set();
368
+ const inflightResolvers = [];
369
+ const subscribers = /* @__PURE__ */ new Set();
370
+ const emit = (state) => {
371
+ currentState = state;
372
+ subscribers.forEach((cb) => cb(state));
373
+ };
374
+ const startOne = (input, resolve, myGeneration) => {
375
+ inFlight++;
376
+ const controller = new AbortController();
377
+ inflightControllers.add(controller);
378
+ inflightResolvers.push(resolve);
379
+ emit(_pending);
380
+ const onRetrying = retryOptions ? (r) => {
381
+ if (generation === myGeneration && inflightControllers.has(controller)) emit(r);
382
+ } : void 0;
383
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
384
+ inflightControllers.delete(controller);
385
+ const idx = inflightResolvers.indexOf(resolve);
386
+ if (idx !== -1) inflightResolvers.splice(idx, 1);
387
+ if (generation !== myGeneration) {
388
+ resolve(_abortedNil);
389
+ return;
390
+ }
391
+ inFlight--;
392
+ emit(outcome);
393
+ resolve(outcome);
394
+ if (queue.length > 0) {
395
+ const next = queue.shift();
396
+ startOne(next.input, next.resolve, generation);
397
+ }
398
+ });
399
+ };
400
+ const run = (input) => {
401
+ const myGeneration = generation;
402
+ if (dedupe !== void 0) {
403
+ const idx = queue.findIndex((item) => dedupe(input, item.input));
404
+ if (idx !== -1) {
405
+ const dup = queue.splice(idx, 1)[0];
406
+ dup.resolve(_droppedNil);
407
+ }
408
+ }
409
+ if (inFlight < maxConcurrency) {
410
+ return Deferred.fromPromise(
411
+ new Promise((resolve) => {
412
+ startOne(input, resolve, myGeneration);
413
+ })
414
+ );
415
+ }
416
+ if (maxSize === void 0 || queue.length < maxSize) {
417
+ return Deferred.fromPromise(
418
+ new Promise((resolve) => {
419
+ queue.push({ input, resolve });
420
+ emit({ kind: "Queued", position: queue.length - 1 });
421
+ })
422
+ );
423
+ }
424
+ if (overflow === "replace-last") {
425
+ return Deferred.fromPromise(
426
+ new Promise((resolve) => {
427
+ const tail = queue.pop();
428
+ tail.resolve(_evictedNil);
429
+ queue.push({ input, resolve });
430
+ emit({ kind: "Queued", position: queue.length - 1 });
431
+ })
432
+ );
433
+ }
434
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
435
+ };
436
+ const abort = () => {
437
+ generation++;
438
+ inflightControllers.forEach((c) => c.abort());
439
+ inflightControllers.clear();
440
+ const toResolve = inflightResolvers.splice(0);
441
+ const queuedResolvers = queue.splice(0).map((item) => item.resolve);
442
+ inFlight = 0;
443
+ if (currentState.kind !== "Idle") emit(_abortedNil);
444
+ toResolve.forEach((r) => r(_abortedNil));
445
+ queuedResolvers.forEach((r) => r(_abortedNil));
446
+ };
447
+ return {
448
+ get state() {
449
+ return currentState;
450
+ },
451
+ run,
452
+ abort,
453
+ subscribe: (cb) => {
454
+ subscribers.add(cb);
455
+ if (currentState.kind !== "Idle") cb(currentState);
456
+ return () => subscribers.delete(cb);
457
+ }
458
+ };
459
+ };
460
+ var makeBuffered = (op, size, retryOptions, timeoutOptions) => {
461
+ const bufferSize = size ?? 1;
462
+ let currentState = _idle;
463
+ let currentController;
464
+ let currentResolve;
465
+ const buffer = [];
466
+ const subscribers = /* @__PURE__ */ new Set();
467
+ const emit = (state) => {
468
+ currentState = state;
469
+ subscribers.forEach((cb) => cb(state));
470
+ };
471
+ const startRun = (input, resolve) => {
472
+ currentResolve = resolve;
473
+ currentController = new AbortController();
474
+ const controller = currentController;
475
+ emit(_pending);
476
+ const onRetrying = retryOptions ? (r) => {
477
+ if (currentController === controller) emit(r);
478
+ } : void 0;
479
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
480
+ if (currentController !== controller) return;
481
+ const r = currentResolve;
482
+ currentResolve = void 0;
483
+ currentController = void 0;
484
+ emit(outcome);
485
+ r?.(outcome);
486
+ if (buffer.length > 0) {
487
+ const next = buffer.shift();
488
+ startRun(next.input, next.resolve);
489
+ }
490
+ });
491
+ };
492
+ const run = (input) => Deferred.fromPromise(
493
+ new Promise((resolve) => {
494
+ if (currentController === void 0) {
495
+ startRun(input, resolve);
496
+ } else if (buffer.length < bufferSize) {
497
+ buffer.push({ input, resolve });
498
+ emit({ kind: "Queued", position: buffer.length - 1 });
499
+ } else {
500
+ const evicted = buffer.shift();
501
+ evicted.resolve(_evictedNil);
502
+ buffer.push({ input, resolve });
503
+ emit({ kind: "Queued", position: buffer.length - 1 });
504
+ }
505
+ })
506
+ );
507
+ const abort = () => {
508
+ currentController?.abort();
509
+ currentController = void 0;
510
+ const cr = currentResolve;
511
+ currentResolve = void 0;
512
+ const bufferedResolvers = buffer.splice(0).map((item) => item.resolve);
513
+ if (currentState.kind !== "Idle") emit(_abortedNil);
514
+ cr?.(_abortedNil);
515
+ bufferedResolvers.forEach((r) => r(_abortedNil));
516
+ };
517
+ return {
518
+ get state() {
519
+ return currentState;
520
+ },
521
+ run,
522
+ abort,
523
+ subscribe: (cb) => {
524
+ subscribers.add(cb);
525
+ if (currentState.kind !== "Idle") cb(currentState);
526
+ return () => subscribers.delete(cb);
527
+ }
528
+ };
529
+ };
530
+ var makeDebounced = (op, ms, leading, maxWait, retryOptions, timeoutOptions) => {
531
+ let currentState = _idle;
532
+ let currentController;
533
+ let currentResolve;
534
+ let leadingController;
535
+ let leadingResolve;
536
+ let pendingResolve;
537
+ let timerId;
538
+ let pendingInput;
539
+ let firstCallAt = 0;
540
+ const subscribers = /* @__PURE__ */ new Set();
541
+ const emit = (state) => {
542
+ currentState = state;
543
+ subscribers.forEach((cb) => cb(state));
544
+ };
545
+ const fireLeading = (input, resolve) => {
546
+ leadingController = new AbortController();
547
+ const controller = leadingController;
548
+ leadingResolve = resolve;
549
+ emit(_pending);
550
+ const onRetrying = retryOptions ? (r) => {
551
+ if (leadingController === controller) emit(r);
552
+ } : void 0;
553
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
554
+ if (leadingController !== controller) return;
555
+ const r = leadingResolve;
556
+ leadingResolve = void 0;
557
+ leadingController = void 0;
558
+ emit(outcome);
559
+ r?.(outcome);
560
+ });
561
+ };
562
+ const fireTrailing = () => {
563
+ timerId = void 0;
564
+ firstCallAt = 0;
565
+ const capturedResolve = pendingResolve;
566
+ pendingResolve = void 0;
567
+ if (capturedResolve === void 0) return;
568
+ currentResolve = capturedResolve;
569
+ const toRun = pendingInput;
570
+ pendingInput = void 0;
571
+ currentController = new AbortController();
572
+ const controller = currentController;
573
+ emit(_pending);
574
+ const onRetrying = retryOptions ? (r) => {
575
+ if (currentController === controller) emit(r);
576
+ } : void 0;
577
+ execute(op, toRun, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
578
+ if (currentController !== controller) return;
579
+ const r = currentResolve;
580
+ currentResolve = void 0;
581
+ currentController = void 0;
582
+ emit(outcome);
583
+ r?.(outcome);
584
+ });
585
+ };
586
+ const scheduleTrailing = () => {
587
+ if (timerId !== void 0) clearTimeout(timerId);
588
+ let delay = ms;
589
+ if (maxWait !== void 0 && firstCallAt > 0) {
590
+ const maxDelay = firstCallAt + maxWait - Date.now();
591
+ delay = Math.min(ms, Math.max(0, maxDelay));
592
+ }
593
+ timerId = setTimeout(fireTrailing, delay);
594
+ };
595
+ const inDebounceWindow = () => timerId !== void 0 || leadingController !== void 0 || currentController !== void 0;
596
+ const run = (input) => Deferred.fromPromise(
597
+ new Promise((resolve) => {
598
+ if (!inDebounceWindow()) {
599
+ firstCallAt = Date.now();
600
+ if (leading) {
601
+ fireLeading(input, resolve);
602
+ scheduleTrailing();
603
+ } else {
604
+ pendingInput = input;
605
+ pendingResolve = resolve;
606
+ scheduleTrailing();
607
+ }
608
+ } else {
609
+ const prev = pendingResolve;
610
+ pendingInput = input;
611
+ pendingResolve = resolve;
612
+ prev?.(_evictedNil);
613
+ scheduleTrailing();
614
+ }
615
+ })
616
+ );
617
+ const abort = () => {
618
+ if (timerId !== void 0) {
619
+ clearTimeout(timerId);
620
+ timerId = void 0;
621
+ pendingInput = void 0;
622
+ firstCallAt = 0;
623
+ }
624
+ const pr = pendingResolve;
625
+ pendingResolve = void 0;
626
+ const cr = currentResolve;
627
+ currentResolve = void 0;
628
+ currentController?.abort();
629
+ currentController = void 0;
630
+ const lr = leadingResolve;
631
+ leadingResolve = void 0;
632
+ leadingController?.abort();
633
+ leadingController = void 0;
634
+ if (currentState.kind !== "Idle") emit(_abortedNil);
635
+ pr?.(_abortedNil);
636
+ cr?.(_abortedNil);
637
+ lr?.(_abortedNil);
638
+ };
639
+ return {
640
+ get state() {
641
+ return currentState;
642
+ },
643
+ run,
644
+ abort,
645
+ subscribe: (cb) => {
646
+ subscribers.add(cb);
647
+ if (currentState.kind !== "Idle") cb(currentState);
648
+ return () => subscribers.delete(cb);
649
+ }
650
+ };
651
+ };
652
+ var makeThrottled = (op, ms, trailing, retryOptions, timeoutOptions) => {
653
+ let currentState = _idle;
654
+ let currentController;
655
+ let currentResolve;
656
+ let cooldownTimer;
657
+ let pendingInput;
658
+ let pendingResolve;
659
+ const subscribers = /* @__PURE__ */ new Set();
660
+ const emit = (state) => {
661
+ currentState = state;
662
+ subscribers.forEach((cb) => cb(state));
663
+ };
664
+ const fireOp = (input, resolve) => {
665
+ currentResolve = resolve;
666
+ currentController = new AbortController();
667
+ const controller = currentController;
668
+ emit(_pending);
669
+ const onRetrying = retryOptions ? (r) => {
670
+ if (currentController === controller) emit(r);
671
+ } : void 0;
672
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
673
+ if (currentController !== controller) return;
674
+ const r = currentResolve;
675
+ currentResolve = void 0;
676
+ currentController = void 0;
677
+ emit(outcome);
678
+ r?.(outcome);
679
+ });
680
+ };
681
+ const startCooldown = () => {
682
+ cooldownTimer = setTimeout(() => {
683
+ cooldownTimer = void 0;
684
+ if (trailing && pendingInput !== void 0) {
685
+ const input = pendingInput;
686
+ const resolve = pendingResolve;
687
+ pendingInput = void 0;
688
+ pendingResolve = void 0;
689
+ fireOp(input, resolve);
690
+ startCooldown();
691
+ }
692
+ }, ms);
693
+ };
694
+ const run = (input) => {
695
+ if (cooldownTimer !== void 0) {
696
+ if (!trailing) {
697
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
698
+ }
699
+ return Deferred.fromPromise(
700
+ new Promise((resolve) => {
701
+ const prev = pendingResolve;
702
+ pendingInput = input;
703
+ pendingResolve = resolve;
704
+ prev?.(_evictedNil);
705
+ })
706
+ );
707
+ }
708
+ return Deferred.fromPromise(
709
+ new Promise((resolve) => {
710
+ fireOp(input, resolve);
711
+ startCooldown();
712
+ })
713
+ );
714
+ };
715
+ const abort = () => {
716
+ if (cooldownTimer !== void 0) {
717
+ clearTimeout(cooldownTimer);
718
+ cooldownTimer = void 0;
719
+ }
720
+ currentController?.abort();
721
+ currentController = void 0;
722
+ const cr = currentResolve;
723
+ currentResolve = void 0;
724
+ const pr = pendingResolve;
725
+ pendingResolve = void 0;
726
+ pendingInput = void 0;
727
+ if (currentState.kind !== "Idle") emit(_abortedNil);
728
+ cr?.(_abortedNil);
729
+ pr?.(_abortedNil);
730
+ };
731
+ return {
732
+ get state() {
733
+ return currentState;
734
+ },
735
+ run,
736
+ abort,
737
+ subscribe: (cb) => {
738
+ subscribers.add(cb);
739
+ if (currentState.kind !== "Idle") cb(currentState);
740
+ return () => subscribers.delete(cb);
741
+ }
742
+ };
743
+ };
744
+ var makeConcurrent = (op, n, overflow, retryOptions, timeoutOptions) => {
745
+ let currentState = _idle;
746
+ let inflight = 0;
747
+ let generation = 0;
748
+ const controllers = /* @__PURE__ */ new Set();
749
+ const inflightResolvers = [];
750
+ const overflowQueue = [];
751
+ const subscribers = /* @__PURE__ */ new Set();
752
+ const emit = (state) => {
753
+ currentState = state;
754
+ subscribers.forEach((cb) => cb(state));
755
+ };
756
+ const startOne = (input, resolve, myGeneration) => {
757
+ inflight++;
758
+ const controller = new AbortController();
759
+ controllers.add(controller);
760
+ inflightResolvers.push(resolve);
761
+ emit(_pending);
762
+ const onRetrying = retryOptions ? (r) => {
763
+ if (generation === myGeneration && controllers.has(controller)) emit(r);
764
+ } : void 0;
765
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
766
+ controllers.delete(controller);
767
+ const idx = inflightResolvers.indexOf(resolve);
768
+ if (idx !== -1) inflightResolvers.splice(idx, 1);
769
+ if (generation !== myGeneration) {
770
+ resolve(_abortedNil);
771
+ return;
772
+ }
773
+ inflight--;
774
+ emit(outcome);
775
+ resolve(outcome);
776
+ if (overflowQueue.length > 0) {
777
+ const next = overflowQueue.shift();
778
+ startOne(next.input, next.resolve, generation);
779
+ }
780
+ });
781
+ };
782
+ const run = (input) => {
783
+ const myGeneration = generation;
784
+ if (inflight < n) {
785
+ return Deferred.fromPromise(
786
+ new Promise((resolve) => {
787
+ startOne(input, resolve, myGeneration);
788
+ })
789
+ );
790
+ }
791
+ if (overflow === "drop") {
792
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
793
+ }
794
+ return Deferred.fromPromise(
795
+ new Promise((resolve) => {
796
+ overflowQueue.push({ input, resolve });
797
+ emit({ kind: "Queued", position: overflowQueue.length - 1 });
798
+ })
799
+ );
800
+ };
801
+ const abort = () => {
802
+ generation++;
803
+ controllers.forEach((c) => c.abort());
804
+ controllers.clear();
805
+ const toResolve = inflightResolvers.splice(0);
806
+ const queuedResolvers = overflowQueue.splice(0).map((item) => item.resolve);
807
+ inflight = 0;
808
+ if (currentState.kind !== "Idle") emit(_abortedNil);
809
+ toResolve.forEach((r) => r(_abortedNil));
810
+ queuedResolvers.forEach((r) => r(_abortedNil));
811
+ };
812
+ return {
813
+ get state() {
814
+ return currentState;
815
+ },
816
+ run,
817
+ abort,
818
+ subscribe: (cb) => {
819
+ subscribers.add(cb);
820
+ if (currentState.kind !== "Idle") cb(currentState);
821
+ return () => subscribers.delete(cb);
822
+ }
823
+ };
824
+ };
825
+ var makeKeyed = (op, keyFn, perKey, timeoutOptions) => {
826
+ const stateMap = /* @__PURE__ */ new Map();
827
+ const slots = /* @__PURE__ */ new Map();
828
+ const subscribers = /* @__PURE__ */ new Set();
829
+ const emitSnapshot = () => {
830
+ const snapshot = new Map(stateMap);
831
+ subscribers.forEach((cb) => cb(snapshot));
832
+ };
833
+ const run = (input) => {
834
+ const k = keyFn(input);
835
+ if (slots.has(k)) {
836
+ if (perKey === "exclusive") {
837
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
838
+ }
839
+ const existing = slots.get(k);
840
+ existing.controller.abort();
841
+ const prev = existing.resolve;
842
+ slots.delete(k);
843
+ prev(_replacedNil);
844
+ }
845
+ return Deferred.fromPromise(
846
+ new Promise((resolve) => {
847
+ const controller = new AbortController();
848
+ slots.set(k, { controller, resolve });
849
+ stateMap.set(k, _pending);
850
+ emitSnapshot();
851
+ execute(op, input, controller, void 0, timeoutOptions, void 0).then((outcome) => {
852
+ const slot = slots.get(k);
853
+ if (!slot || slot.controller !== controller) {
854
+ resolve(_abortedNil);
855
+ return;
856
+ }
857
+ slots.delete(k);
858
+ stateMap.set(k, outcome);
859
+ emitSnapshot();
860
+ resolve(outcome);
861
+ });
862
+ })
863
+ );
864
+ };
865
+ const abort = (key) => {
866
+ if (key !== void 0) {
867
+ const slot = slots.get(key);
868
+ if (slot) {
869
+ slot.controller.abort();
870
+ const r = slot.resolve;
871
+ slots.delete(key);
872
+ stateMap.set(key, _abortedNil);
873
+ emitSnapshot();
874
+ r(_abortedNil);
875
+ }
876
+ } else {
877
+ const toResolve = [];
878
+ for (const [k, slot] of slots) {
879
+ slot.controller.abort();
880
+ toResolve.push(slot.resolve);
881
+ stateMap.set(k, _abortedNil);
882
+ }
883
+ slots.clear();
884
+ if (toResolve.length > 0) emitSnapshot();
885
+ toResolve.forEach((r) => r(_abortedNil));
886
+ }
887
+ };
888
+ return {
889
+ get state() {
890
+ return new Map(stateMap);
891
+ },
892
+ run,
893
+ abort,
894
+ subscribe: (cb) => {
895
+ subscribers.add(cb);
896
+ if (stateMap.size > 0) cb(new Map(stateMap));
897
+ return () => subscribers.delete(cb);
898
+ }
899
+ };
900
+ };
901
+ var makeOnce = (op, retryOptions, timeoutOptions) => {
902
+ let currentState = _idle;
903
+ let currentController;
904
+ let currentResolve;
905
+ const subscribers = /* @__PURE__ */ new Set();
906
+ const emit = (state) => {
907
+ currentState = state;
908
+ subscribers.forEach((cb) => cb(state));
909
+ };
910
+ const run = (input) => {
911
+ if (currentState.kind !== "Idle") {
912
+ return Deferred.fromPromise(Promise.resolve(_droppedNil));
913
+ }
914
+ return Deferred.fromPromise(
915
+ new Promise((resolve) => {
916
+ currentResolve = resolve;
917
+ currentController = new AbortController();
918
+ const controller = currentController;
919
+ emit(_pending);
920
+ const onRetrying = retryOptions ? (r) => {
921
+ if (currentController === controller) emit(r);
922
+ } : void 0;
923
+ execute(op, input, controller, retryOptions, timeoutOptions, onRetrying).then((outcome) => {
924
+ if (currentController !== controller) return;
925
+ const r = currentResolve;
926
+ currentResolve = void 0;
927
+ currentController = void 0;
928
+ emit(outcome);
929
+ r?.(outcome);
930
+ });
931
+ })
932
+ );
933
+ };
934
+ const abort = () => {
935
+ currentController?.abort();
936
+ currentController = void 0;
937
+ const r = currentResolve;
938
+ currentResolve = void 0;
939
+ if (currentState.kind !== "Idle") emit(_abortedNil);
940
+ r?.(_abortedNil);
941
+ };
942
+ return {
943
+ get state() {
944
+ return currentState;
945
+ },
946
+ run,
947
+ abort,
948
+ subscribe: (cb) => {
949
+ subscribers.add(cb);
950
+ if (currentState.kind !== "Idle") cb(currentState);
951
+ return () => subscribers.delete(cb);
952
+ }
953
+ };
954
+ };
955
+
956
+ // src/Core/Op.ts
957
+ var Op;
958
+ ((Op2) => {
959
+ Op2.nil = (reason) => ({ kind: "Nil", reason });
960
+ Op2.create = (factory, onError) => ({
961
+ _factory: (input, signal) => Deferred.fromPromise(
962
+ factory(input, signal).then((value) => Result.ok(value)).catch((e) => signal.aborted ? null : Result.err(onError(e)))
963
+ )
964
+ });
965
+ Op2.ok = (value) => ({ kind: "Ok", value });
966
+ Op2.err = (error) => ({ kind: "Err", error });
967
+ Op2.isOk = (outcome) => outcome.kind === "Ok";
968
+ Op2.isErr = (outcome) => outcome.kind === "Err";
969
+ Op2.isNil = (outcome) => outcome.kind === "Nil";
970
+ Op2.match = (cases) => (outcome) => {
971
+ if (outcome.kind === "Ok") return cases.ok(outcome.value);
972
+ if (outcome.kind === "Err") return cases.err(outcome.error);
973
+ return cases.nil();
974
+ };
975
+ Op2.fold = (onErr, onOk, onNil) => (outcome) => {
976
+ if (outcome.kind === "Ok") return onOk(outcome.value);
977
+ if (outcome.kind === "Err") return onErr(outcome.error);
978
+ return onNil();
979
+ };
980
+ Op2.getOrElse = (defaultValue) => (outcome) => outcome.kind === "Ok" ? outcome.value : defaultValue();
981
+ Op2.map = (f) => (outcome) => outcome.kind === "Ok" ? (0, Op2.ok)(f(outcome.value)) : outcome;
982
+ Op2.mapError = (f) => (outcome) => outcome.kind === "Err" ? (0, Op2.err)(f(outcome.error)) : outcome;
983
+ Op2.chain = (f) => (outcome) => outcome.kind === "Ok" ? f(outcome.value) : outcome;
984
+ Op2.tap = (f) => (outcome) => {
985
+ if (outcome.kind === "Ok") f(outcome.value);
986
+ return outcome;
987
+ };
988
+ Op2.recover = (f) => (outcome) => outcome.kind === "Err" ? f(outcome.error) : outcome;
989
+ Op2.toResult = (onNil) => (outcome) => {
990
+ if (outcome.kind === "Ok") return Result.ok(outcome.value);
991
+ if (outcome.kind === "Err") return Result.err(outcome.error);
992
+ return Result.err(onNil());
993
+ };
994
+ Op2.toMaybe = (outcome) => outcome.kind === "Ok" ? Maybe.some(outcome.value) : Maybe.none();
995
+ Op2.all = (invocations) => Deferred.fromPromise(Promise.all(invocations.map(Deferred.toPromise)));
996
+ Op2.race = (invocations) => Deferred.fromPromise(Promise.race(invocations.map(Deferred.toPromise)));
997
+ function interpret(op, options) {
998
+ const { strategy, retry: retryOptions, timeout: timeoutOptions } = options;
999
+ switch (strategy) {
1000
+ case "once":
1001
+ return makeOnce(op, retryOptions, timeoutOptions);
1002
+ case "restartable":
1003
+ return makeRestartable(op, options.minInterval, retryOptions, timeoutOptions);
1004
+ case "exclusive":
1005
+ return makeExclusive(op, options.cooldown, retryOptions, timeoutOptions);
1006
+ case "queue":
1007
+ return makeQueue(
1008
+ op,
1009
+ options.maxSize,
1010
+ options.overflow,
1011
+ options.concurrency,
1012
+ options.dedupe,
1013
+ retryOptions,
1014
+ timeoutOptions
1015
+ );
1016
+ case "buffered":
1017
+ return makeBuffered(op, options.size, retryOptions, timeoutOptions);
1018
+ case "debounced":
1019
+ return makeDebounced(op, options.ms ?? 0, options.leading ?? false, options.maxWait, retryOptions, timeoutOptions);
1020
+ case "throttled":
1021
+ return makeThrottled(op, options.ms ?? 0, options.trailing ?? false, retryOptions, timeoutOptions);
1022
+ case "concurrent":
1023
+ return makeConcurrent(
1024
+ op,
1025
+ options.n ?? 1,
1026
+ options.overflow ?? "drop",
1027
+ retryOptions,
1028
+ timeoutOptions
1029
+ );
1030
+ case "keyed":
1031
+ return makeKeyed(op, options.key ?? ((i) => i), options.perKey ?? "exclusive", timeoutOptions);
1032
+ }
1033
+ }
1034
+ Op2.interpret = interpret;
1035
+ })(Op || (Op = {}));
1036
+
164
1037
  // src/Core/Optional.ts
165
1038
  var Optional;
166
1039
  ((Optional2) => {
@@ -328,77 +1201,99 @@ var RemoteData;
328
1201
  })(RemoteData || (RemoteData = {}));
329
1202
 
330
1203
  // src/Core/Task.ts
331
- var toPromise = (task) => Deferred.toPromise(task());
1204
+ var toPromise = (task, signal) => Deferred.toPromise(task(signal));
332
1205
  var Task;
333
1206
  ((Task2) => {
334
1207
  Task2.resolve = (value) => () => Deferred.fromPromise(Promise.resolve(value));
335
- Task2.from = (f) => () => Deferred.fromPromise(f());
336
- Task2.map = (f) => (data) => (0, Task2.from)(() => toPromise(data).then(f));
337
- Task2.chain = (f) => (data) => (0, Task2.from)(() => toPromise(data).then((a) => toPromise(f(a))));
1208
+ Task2.from = (f) => (signal) => Deferred.fromPromise(f(signal));
1209
+ Task2.map = (f) => (data) => (0, Task2.from)((signal) => toPromise(data, signal).then(f));
1210
+ Task2.chain = (f) => (data) => (0, Task2.from)((signal) => toPromise(data, signal).then((a) => toPromise(f(a), signal)));
338
1211
  Task2.ap = (arg) => (data) => (0, Task2.from)(
339
- () => Promise.all([
340
- toPromise(data),
341
- toPromise(arg)
1212
+ (signal) => Promise.all([
1213
+ toPromise(data, signal),
1214
+ toPromise(arg, signal)
342
1215
  ]).then(([f, a]) => f(a))
343
1216
  );
344
1217
  Task2.tap = (f) => (data) => (0, Task2.from)(
345
- () => toPromise(data).then((a) => {
1218
+ (signal) => toPromise(data, signal).then((a) => {
346
1219
  f(a);
347
1220
  return a;
348
1221
  })
349
1222
  );
350
1223
  Task2.all = (tasks) => (0, Task2.from)(
351
- () => Promise.all(tasks.map((t) => toPromise(t)))
1224
+ (signal) => Promise.all(tasks.map((t) => toPromise(t, signal)))
352
1225
  );
353
1226
  Task2.delay = (ms) => (data) => (0, Task2.from)(
354
- () => new Promise(
1227
+ (signal) => new Promise(
355
1228
  (resolve2) => setTimeout(
356
- () => toPromise(data).then(resolve2),
1229
+ () => toPromise(data, signal).then(resolve2),
357
1230
  ms
358
1231
  )
359
1232
  )
360
1233
  );
361
- Task2.repeat = (options) => (task) => (0, Task2.from)(() => {
1234
+ Task2.repeat = (options) => (task) => (0, Task2.from)((signal) => {
362
1235
  const { times, delay: ms } = options;
363
1236
  if (times <= 0) return Promise.resolve([]);
364
1237
  const results = [];
365
1238
  const wait = () => ms !== void 0 && ms > 0 ? new Promise((r) => setTimeout(r, ms)) : Promise.resolve();
366
- const run = (left) => toPromise(task).then((a) => {
1239
+ const run = (left) => toPromise(task, signal).then((a) => {
367
1240
  results.push(a);
368
1241
  if (left <= 1) return results;
369
1242
  return wait().then(() => run(left - 1));
370
1243
  });
371
1244
  return run(times);
372
1245
  });
373
- Task2.repeatUntil = (options) => (task) => (0, Task2.from)(() => {
1246
+ Task2.repeatUntil = (options) => (task) => (0, Task2.from)((signal) => {
374
1247
  const { when: predicate, delay: ms } = options;
375
1248
  const wait = () => ms !== void 0 && ms > 0 ? new Promise((r) => setTimeout(r, ms)) : Promise.resolve();
376
- const run = () => toPromise(task).then((a) => {
1249
+ const run = () => toPromise(task, signal).then((a) => {
377
1250
  if (predicate(a)) return a;
378
1251
  return wait().then(run);
379
1252
  });
380
1253
  return run();
381
1254
  });
382
- Task2.race = (tasks) => (0, Task2.from)(() => Promise.race(tasks.map(toPromise)));
383
- Task2.sequential = (tasks) => (0, Task2.from)(async () => {
1255
+ Task2.race = (tasks) => (0, Task2.from)((signal) => Promise.race(tasks.map((t) => toPromise(t, signal))));
1256
+ Task2.sequential = (tasks) => (0, Task2.from)(async (signal) => {
384
1257
  const results = [];
385
1258
  for (const task of tasks) {
386
- results.push(await toPromise(task));
1259
+ results.push(await toPromise(task, signal));
387
1260
  }
388
1261
  return results;
389
1262
  });
390
- Task2.timeout = (ms, onTimeout) => (task) => (0, Task2.from)(() => {
1263
+ Task2.timeout = (ms, onTimeout) => (task) => (0, Task2.from)((outerSignal) => {
1264
+ const controller = new AbortController();
1265
+ const onOuterAbort = () => controller.abort();
1266
+ outerSignal?.addEventListener("abort", onOuterAbort, { once: true });
391
1267
  let timerId;
392
1268
  return Promise.race([
393
- toPromise(task).then((a) => {
1269
+ toPromise(task, controller.signal).then((a) => {
394
1270
  clearTimeout(timerId);
1271
+ outerSignal?.removeEventListener("abort", onOuterAbort);
395
1272
  return Result.ok(a);
396
1273
  }),
397
1274
  new Promise((resolve2) => {
398
- timerId = setTimeout(() => resolve2(Result.err(onTimeout())), ms);
1275
+ timerId = setTimeout(() => {
1276
+ controller.abort();
1277
+ outerSignal?.removeEventListener("abort", onOuterAbort);
1278
+ resolve2(Result.err(onTimeout()));
1279
+ }, ms);
399
1280
  })
400
1281
  ]);
401
1282
  });
1283
+ Task2.abortable = (factory) => {
1284
+ const controller = new AbortController();
1285
+ const task = (outerSignal) => {
1286
+ if (outerSignal) {
1287
+ if (outerSignal.aborted) {
1288
+ controller.abort(outerSignal.reason);
1289
+ } else {
1290
+ outerSignal.addEventListener("abort", () => controller.abort(outerSignal.reason), { once: true });
1291
+ }
1292
+ }
1293
+ return Deferred.fromPromise(factory(controller.signal));
1294
+ };
1295
+ return { task, abort: () => controller.abort() };
1296
+ };
402
1297
  })(Task || (Task = {}));
403
1298
 
404
1299
  // src/Core/Resource.ts
@@ -498,7 +1393,7 @@ var TaskResult;
498
1393
  TaskResult2.ok = (value) => Task.resolve(Result.ok(value));
499
1394
  TaskResult2.err = (error) => Task.resolve(Result.err(error));
500
1395
  TaskResult2.tryCatch = (f, onError) => Task.from(
501
- () => f().then(Result.ok).catch((e) => Result.err(onError(e)))
1396
+ (signal) => f(signal).then(Result.ok).catch((e) => Result.err(onError(e)))
502
1397
  );
503
1398
  TaskResult2.map = (f) => (data) => Task.map(Result.map(f))(data);
504
1399
  TaskResult2.mapError = (f) => (data) => Task.map(Result.mapError(f))(data);
@@ -512,43 +1407,6 @@ var TaskResult;
512
1407
  )(data);
513
1408
  TaskResult2.getOrElse = (defaultValue) => (data) => Task.map(Result.getOrElse(defaultValue))(data);
514
1409
  TaskResult2.tap = (f) => (data) => Task.map(Result.tap(f))(data);
515
- TaskResult2.retry = (options) => (data) => Task.from(() => {
516
- const { attempts, backoff, when: shouldRetry } = options;
517
- const getDelay = (n) => backoff === void 0 ? 0 : typeof backoff === "function" ? backoff(n) : backoff;
518
- const run = (left) => Deferred.toPromise(data()).then((result) => {
519
- if (Result.isOk(result)) return result;
520
- if (left <= 1) return result;
521
- if (shouldRetry !== void 0 && !shouldRetry(result.error)) {
522
- return result;
523
- }
524
- const ms = getDelay(attempts - left + 1);
525
- return (ms > 0 ? new Promise((r) => setTimeout(r, ms)) : Promise.resolve()).then(() => run(left - 1));
526
- });
527
- return run(attempts);
528
- });
529
- TaskResult2.pollUntil = (options) => (task) => Task.from(() => {
530
- const { when: predicate, delay } = options;
531
- const getDelay = (attempt) => delay === void 0 ? 0 : typeof delay === "function" ? delay(attempt) : delay;
532
- const run = (attempt) => Deferred.toPromise(task()).then((result) => {
533
- if (Result.isErr(result)) return result;
534
- if (predicate(result.value)) return result;
535
- const ms = getDelay(attempt);
536
- return (ms > 0 ? new Promise((r) => setTimeout(r, ms)) : Promise.resolve()).then(() => run(attempt + 1));
537
- });
538
- return run(1);
539
- });
540
- TaskResult2.timeout = (ms, onTimeout) => (data) => Task.from(() => {
541
- let timerId;
542
- return Promise.race([
543
- Deferred.toPromise(data()).then((result) => {
544
- clearTimeout(timerId);
545
- return result;
546
- }),
547
- new Promise((resolve) => {
548
- timerId = setTimeout(() => resolve(Result.err(onTimeout())), ms);
549
- })
550
- ]);
551
- });
552
1410
  })(TaskResult || (TaskResult = {}));
553
1411
 
554
1412
  // src/Core/Validation.ts
@@ -585,7 +1443,7 @@ var Validation;
585
1443
  return data;
586
1444
  };
587
1445
  Validation2.recover = (fallback) => (data) => (0, Validation2.isValid)(data) ? data : fallback(data.errors);
588
- Validation2.recoverUnless = (blockedErrors, fallback) => (data) => (0, Validation2.isInvalid)(data) && !data.errors.some((err) => blockedErrors.includes(err)) ? fallback() : data;
1446
+ Validation2.recoverUnless = (blockedErrors, fallback) => (data) => (0, Validation2.isInvalid)(data) && !data.errors.some((err2) => blockedErrors.includes(err2)) ? fallback() : data;
589
1447
  Validation2.product = (first, second) => {
590
1448
  if ((0, Validation2.isValid)(first) && (0, Validation2.isValid)(second)) return (0, Validation2.valid)([first.value, second.value]);
591
1449
  const errors = [
@@ -727,6 +1585,7 @@ var Tuple;
727
1585
  Lens,
728
1586
  Logged,
729
1587
  Maybe,
1588
+ Op,
730
1589
  Optional,
731
1590
  Predicate,
732
1591
  Reader,