@openstage/monadyssey-core 3.0.0-rc.2 → 3.0.0-rc.4
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/monadyssey.d.ts +569 -48
- package/dist/monadyssey.mjs +6034 -1436
- package/dist/monadyssey.mjs.map +1 -1
- package/package.json +1 -1
- package/readme.md +5 -0
package/dist/monadyssey.d.ts
CHANGED
|
@@ -2,10 +2,20 @@ export declare interface Cancelled {
|
|
|
2
2
|
readonly type: "Cancelled";
|
|
3
3
|
}
|
|
4
4
|
|
|
5
|
+
/** How many items `parTraverse` / `parSequence` run at once. */
|
|
6
|
+
declare interface Concurrency {
|
|
7
|
+
/** At most this many items run at once: a positive integer, or `Infinity` (the default). */
|
|
8
|
+
readonly concurrency?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
5
11
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
12
|
+
* A run that ended with a defect: an exception that was not declared as an `E`. It carries no
|
|
13
|
+
* exception; the defect itself still reaches `unsafeRun()` / `join()`.
|
|
8
14
|
*/
|
|
15
|
+
export declare interface Defect {
|
|
16
|
+
readonly type: "Defect";
|
|
17
|
+
}
|
|
18
|
+
|
|
9
19
|
export declare abstract class Either<A, B> {
|
|
10
20
|
abstract readonly type: "Left" | "Right";
|
|
11
21
|
/**
|
|
@@ -139,6 +149,46 @@ export declare abstract class Either<A, B> {
|
|
|
139
149
|
* Left.of('Error').tapLeft(err => console.log(err)); // Logs "Error"
|
|
140
150
|
*/
|
|
141
151
|
abstract tapLeft(action: (left: A) => void): Either<A, B>;
|
|
152
|
+
/**
|
|
153
|
+
* Applicative combine of independent `Either`s ("applicative for"): collects *every* `Left`
|
|
154
|
+
* into a `NonEmptyList`, in argument order, instead of stopping at the first. When all are
|
|
155
|
+
* `Right`, the last argument combines their values (in argument order). Use it to validate
|
|
156
|
+
* several fields and report every failure at once; {@link forM} stops at the first `Left`.
|
|
157
|
+
*
|
|
158
|
+
* Each `Either` may have a different error type; the result's is `NonEmptyList<E1 | E2 | …>`.
|
|
159
|
+
*
|
|
160
|
+
* @example
|
|
161
|
+
* const form = Either.forA(
|
|
162
|
+
* required("name", input.name), // Either<FieldError, string>
|
|
163
|
+
* validEmail(input.email), // Either<FieldError, Email>
|
|
164
|
+
* (name, email) => ({ name, email })
|
|
165
|
+
* ); // Either<NonEmptyList<FieldError>, { name, email }>
|
|
166
|
+
*/
|
|
167
|
+
static forA<E1, E2, A1, A2, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, f: (a1: A1, a2: A2) => R): Either<NonEmptyList<E1 | E2>, R>;
|
|
168
|
+
static forA<E1, E2, E3, A1, A2, A3, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, f: (a1: A1, a2: A2, a3: A3) => R): Either<NonEmptyList<E1 | E2 | E3>, R>;
|
|
169
|
+
static forA<E1, E2, E3, E4, A1, A2, A3, A4, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, f: (a1: A1, a2: A2, a3: A3, a4: A4) => R): Either<NonEmptyList<E1 | E2 | E3 | E4>, R>;
|
|
170
|
+
static forA<E1, E2, E3, E4, E5, A1, A2, A3, A4, A5, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, e5: Either<E5, A5>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => R): Either<NonEmptyList<E1 | E2 | E3 | E4 | E5>, R>;
|
|
171
|
+
static forA<E1, E2, E3, E4, E5, E6, A1, A2, A3, A4, A5, A6, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, e5: Either<E5, A5>, e6: Either<E6, A6>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => R): Either<NonEmptyList<E1 | E2 | E3 | E4 | E5 | E6>, R>;
|
|
172
|
+
static forA<E1, E2, E3, E4, E5, E6, E7, A1, A2, A3, A4, A5, A6, A7, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, e5: Either<E5, A5>, e6: Either<E6, A6>, e7: Either<E7, A7>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => R): Either<NonEmptyList<E1 | E2 | E3 | E4 | E5 | E6 | E7>, R>;
|
|
173
|
+
static forA<E1, E2, E3, E4, E5, E6, E7, E8, A1, A2, A3, A4, A5, A6, A7, A8, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, e5: Either<E5, A5>, e6: Either<E6, A6>, e7: Either<E7, A7>, e8: Either<E8, A8>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => R): Either<NonEmptyList<E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8>, R>;
|
|
174
|
+
static forA<E1, E2, E3, E4, E5, E6, E7, E8, E9, A1, A2, A3, A4, A5, A6, A7, A8, A9, R>(e1: Either<E1, A1>, e2: Either<E2, A2>, e3: Either<E3, A3>, e4: Either<E4, A4>, e5: Either<E5, A5>, e6: Either<E6, A6>, e7: Either<E7, A7>, e8: Either<E8, A8>, e9: Either<E9, A9>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9) => R): Either<NonEmptyList<E1 | E2 | E3 | E4 | E5 | E6 | E7 | E8 | E9>, R>;
|
|
175
|
+
/**
|
|
176
|
+
* Monadic comprehension ("monadic for") over `Either`, synchronous. Inside `operation`,
|
|
177
|
+
* `$(either)` returns the `Right` value; the first `Left` stops the body, and `forM` returns
|
|
178
|
+
* that `Left`. The body's return value becomes the `Right`. An exception that is not a `Left`
|
|
179
|
+
* is not caught: it propagates from `forM`. Use {@link forA} to collect every `Left` instead.
|
|
180
|
+
*
|
|
181
|
+
* `$` stops the body by throwing, so a `try` / `catch` in the body must rethrow what it does
|
|
182
|
+
* not handle, and the body must be synchronous.
|
|
183
|
+
*
|
|
184
|
+
* @example
|
|
185
|
+
* const total = Either.forM<ParseError, number>(($) => {
|
|
186
|
+
* const price = $(parsePrice(input.price));
|
|
187
|
+
* const quantity = $(parseQuantity(input.quantity));
|
|
188
|
+
* return price * quantity;
|
|
189
|
+
* });
|
|
190
|
+
*/
|
|
191
|
+
static forM<E, A>(operation: ($: <B>(either: Either<E, B>) => B) => A & NotThenable): Either<E, A>;
|
|
142
192
|
}
|
|
143
193
|
|
|
144
194
|
/**
|
|
@@ -344,10 +394,74 @@ export declare class EvaluationError<E> extends Error {
|
|
|
344
394
|
|
|
345
395
|
/**
|
|
346
396
|
* The outcome of a run: a value, a typed error, or cancellation. A forked fiber's `join()` resolves to
|
|
347
|
-
* an `Exit`; `unsafeRun()` cannot be cancelled
|
|
397
|
+
* an `Exit`, and so does `unsafeRun({ signal })`; `unsafeRun()` without a signal cannot be cancelled
|
|
398
|
+
* from outside, so it yields `Ok<A> | Err<E>`.
|
|
348
399
|
*/
|
|
349
400
|
export declare type Exit<E, A> = Ok<A> | Err<E> | Cancelled;
|
|
350
401
|
|
|
402
|
+
export declare const Exit: {
|
|
403
|
+
/**
|
|
404
|
+
* Maps each case of an exit to a single type. Every case the exit's type can be needs a handler, so
|
|
405
|
+
* a missing one is a compile error: an `Exit` takes `onOk`, `onErr` and `onCancelled`, a
|
|
406
|
+
* `ReleaseExit` also takes `onDefect`, and what `unsafeRun()` without a signal returns takes `onOk`
|
|
407
|
+
* and `onErr` only.
|
|
408
|
+
*
|
|
409
|
+
* @template X The type of the exit.
|
|
410
|
+
* @template B The result type of every handler.
|
|
411
|
+
* @param {X} exit The exit to fold: what `unsafeRun()` or `fiber.join()` resolves to, or what a
|
|
412
|
+
* `bracket` release receives.
|
|
413
|
+
* @param handlers One handler for each case of `X`.
|
|
414
|
+
* @returns {B} What the handler of the exit's case returns.
|
|
415
|
+
* @throws {TypeError} When `exit` is not an exit: its `type` is not `Ok`, `Err`, `Cancelled` or `Defect`.
|
|
416
|
+
*
|
|
417
|
+
* @example
|
|
418
|
+
* const status = Exit.fold(await fiber.join(), {
|
|
419
|
+
* onOk: (user) => `loaded ${user.id}`,
|
|
420
|
+
* onErr: (error) => `failed: ${error.message}`,
|
|
421
|
+
* onCancelled: () => "stopped",
|
|
422
|
+
* });
|
|
423
|
+
*
|
|
424
|
+
* @example
|
|
425
|
+
* // A bracket release that acts on how `use` ended.
|
|
426
|
+
* IO.bracket(connect(), work, (conn, exit) =>
|
|
427
|
+
* Exit.fold(exit, {
|
|
428
|
+
* onOk: () => IO.sync(() => conn.release()),
|
|
429
|
+
* onErr: () => rollback(conn),
|
|
430
|
+
* onCancelled: () => IO.sync(() => conn.destroy()),
|
|
431
|
+
* onDefect: () => IO.sync(() => conn.destroy()),
|
|
432
|
+
* })
|
|
433
|
+
* );
|
|
434
|
+
*/
|
|
435
|
+
fold: <X extends ReleaseExit<unknown, unknown>, B>(exit: X, handlers: ExitHandlers<X, B>) => B;
|
|
436
|
+
};
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* The handlers `Exit.fold` takes for an exit of type `X`: one for each case `X` can be, and none for
|
|
440
|
+
* the others. A handler for a case `X` cannot be is refused, so `onDefect` belongs to a `ReleaseExit`
|
|
441
|
+
* only, and `onCancelled` is refused for what `unsafeRun()` without a signal returns.
|
|
442
|
+
*/
|
|
443
|
+
declare type ExitHandlers<X extends ReleaseExit<unknown, unknown>, B> = ("Ok" extends X["type"] ? {
|
|
444
|
+
readonly onOk: (value: Extract<X, {
|
|
445
|
+
readonly type: "Ok";
|
|
446
|
+
}>["value"]) => B;
|
|
447
|
+
} : {
|
|
448
|
+
readonly onOk?: never;
|
|
449
|
+
}) & ("Err" extends X["type"] ? {
|
|
450
|
+
readonly onErr: (error: Extract<X, {
|
|
451
|
+
readonly type: "Err";
|
|
452
|
+
}>["error"]) => B;
|
|
453
|
+
} : {
|
|
454
|
+
readonly onErr?: never;
|
|
455
|
+
}) & ("Cancelled" extends X["type"] ? {
|
|
456
|
+
readonly onCancelled: () => B;
|
|
457
|
+
} : {
|
|
458
|
+
readonly onCancelled?: never;
|
|
459
|
+
}) & ("Defect" extends X["type"] ? {
|
|
460
|
+
readonly onDefect: () => B;
|
|
461
|
+
} : {
|
|
462
|
+
readonly onDefect?: never;
|
|
463
|
+
});
|
|
464
|
+
|
|
351
465
|
export declare interface Fiber<E, A> {
|
|
352
466
|
/**
|
|
353
467
|
* Wait for the computation to complete. Rejects with the original exception on a defect. A
|
|
@@ -361,6 +475,19 @@ export declare interface Fiber<E, A> {
|
|
|
361
475
|
readonly signal: AbortSignal;
|
|
362
476
|
}
|
|
363
477
|
|
|
478
|
+
/** Options for {@link IO.fork} and {@link IO.forkDaemon}. */
|
|
479
|
+
export declare interface ForkOptions {
|
|
480
|
+
/**
|
|
481
|
+
* Receives the defect of the fiber when nobody joins it, right after the defect happens (one
|
|
482
|
+
* macrotask later), for `fork` and `forkDaemon` alike: the forking run keeps no record of the
|
|
483
|
+
* fiber, so a long-running run can fork any number of them. It is not called when the fiber is
|
|
484
|
+
* joined first (`join()` rejects with the defect as usual), nor for a typed error or a
|
|
485
|
+
* cancellation. A fiber joined after the handler was called still rejects `join()` with the
|
|
486
|
+
* defect. If the handler throws, that exception is reported as an unhandled rejection instead.
|
|
487
|
+
*/
|
|
488
|
+
readonly onDefect?: (cause: unknown) => void;
|
|
489
|
+
}
|
|
490
|
+
|
|
364
491
|
/**
|
|
365
492
|
* `Ordering.GT` as a bare module constant.
|
|
366
493
|
*
|
|
@@ -484,8 +611,8 @@ export declare class IO<E, A> {
|
|
|
484
611
|
* Creates an IO from a function that receives an `AbortSignal` for cooperative cancellation.
|
|
485
612
|
* Use this when the underlying operation supports cancellation (e.g., `fetch`, streams, timers).
|
|
486
613
|
*
|
|
487
|
-
* The signal is
|
|
488
|
-
*
|
|
614
|
+
* The signal is the run's: a fiber's, a `timeout`'s or `race`'s, or the one passed to
|
|
615
|
+
* `unsafeRun({ signal })`. Under a plain `unsafeRun()`, the signal is never aborted.
|
|
489
616
|
*
|
|
490
617
|
* On cancellation the interpreter does not wait for the returned promise: it runs the
|
|
491
618
|
* finalizers and reports `Cancelled` straight away, and `f` is expected to stop its own work
|
|
@@ -517,9 +644,11 @@ export declare class IO<E, A> {
|
|
|
517
644
|
* Semantics:
|
|
518
645
|
* - If **acquire** fails, or is cancelled before producing a resource, `use` and `release` are
|
|
519
646
|
* never called.
|
|
520
|
-
* -
|
|
521
|
-
*
|
|
522
|
-
*
|
|
647
|
+
* - If cancellation arrives while **acquire** runs, the bracket ends as `Cancelled` at once,
|
|
648
|
+
* without waiting for it: a slow acquire cannot hold a cancellation or a timeout. A resource
|
|
649
|
+
* it still produces later is released as soon as it arrives, with `Cancelled` as the exit. (A
|
|
650
|
+
* cancellable acquire sees the signal and may stop early. To keep a step from being left
|
|
651
|
+
* behind, such as a commit, use {@link IO.uncancellable}.)
|
|
523
652
|
* - If **use** succeeds, `release` runs and the success value is returned.
|
|
524
653
|
* - If **use** fails, `release` runs and the original error is returned.
|
|
525
654
|
* - If **use** is cancelled, `release` runs and `Cancelled` is propagated.
|
|
@@ -562,7 +691,34 @@ export declare class IO<E, A> {
|
|
|
562
691
|
* (pool) => IO.promise(() => pool.shutdown())
|
|
563
692
|
* ).mapErr(e => new AppError(e));
|
|
564
693
|
*/
|
|
565
|
-
static bracket<E, F, R, A>(acquire: IO<E, R>, use: (r: R) => IO<F, A>, release: (r: R) => IO<never, void>): IO<E | F, A>;
|
|
694
|
+
static bracket<E, F, R, A>(acquire: IO<E, R>, use: (r: R) => IO<F, A>, release: (r: R, exit: ReleaseExit<F, A>) => IO<never, void>): IO<E | F, A>;
|
|
695
|
+
/**
|
|
696
|
+
* Runs `io` to its end even when the run is cancelled while it runs. The cancellation takes
|
|
697
|
+
* effect right after `io` ends: the run then ends as `Cancelled`, and `io`'s value or error is
|
|
698
|
+
* dropped. Use it for a step that must not be abandoned half-way, such as a database commit, an
|
|
699
|
+
* `fsync` after a rename, or acknowledging a message.
|
|
700
|
+
*
|
|
701
|
+
* - The effects inside never see an abort: the signal they receive does not abort while they run.
|
|
702
|
+
* - An enclosing `timeout` or a lost `race` waits for `io` to end before it settles.
|
|
703
|
+
* - A run that is already cancelled when it reaches this step does not start `io`.
|
|
704
|
+
* - A fiber forked inside is a child of the outer run, but the outer cancellation reaches it only
|
|
705
|
+
* when `io` ends, so `io` can still join it. After that, it is cancelled with the outer run like
|
|
706
|
+
* any other child. A `forkDaemon` fiber has no parent, here as anywhere else.
|
|
707
|
+
*
|
|
708
|
+
* Failures and defects of `io` pass through unchanged.
|
|
709
|
+
*
|
|
710
|
+
* @template E The error type of `io`.
|
|
711
|
+
* @template A The success type of `io`.
|
|
712
|
+
* @param {IO<E, A>} io The IO to protect from cancellation.
|
|
713
|
+
* @returns {IO<E, A>} An IO that runs `io` to its end.
|
|
714
|
+
*
|
|
715
|
+
* @example
|
|
716
|
+
* const transaction = (conn: Connection): IO<DbError, Order> =>
|
|
717
|
+
* insertOrder(conn).flatMap((order) =>
|
|
718
|
+
* IO.uncancellable(IO.lift(() => conn.commit(), toDbError)).map(() => order)
|
|
719
|
+
* );
|
|
720
|
+
*/
|
|
721
|
+
static uncancellable<E, A>(io: IO<E, A>): IO<E, A>;
|
|
566
722
|
/**
|
|
567
723
|
* Lifts an already-computed value into IO with no side effect.
|
|
568
724
|
* The value is available immediately — no deferred computation takes place.
|
|
@@ -740,8 +896,10 @@ export declare class IO<E, A> {
|
|
|
740
896
|
* If this IO fails, the function is not called. The callback may be synchronous
|
|
741
897
|
* or asynchronous — the interpreter awaits if it returns a Promise.
|
|
742
898
|
*
|
|
743
|
-
* If the side-effect throws,
|
|
744
|
-
*
|
|
899
|
+
* If the side-effect throws or rejects, that is a **defect**, as a throw in `map` is: it is not
|
|
900
|
+
* an `E`, and `unsafeRun()` rejects with it. For a side effect that may fail and whose failure
|
|
901
|
+
* should be ignored, catch it inside the callback; for one whose failure is an `E`, use
|
|
902
|
+
* `flatMap` with an `IO.lift(f, liftE)`.
|
|
745
903
|
*
|
|
746
904
|
* @param {(a: A) => void | Promise<void>} f The side-effect function.
|
|
747
905
|
* @returns {IO<E, A>} A new IO that performs the side-effect but preserves the original result.
|
|
@@ -755,8 +913,9 @@ export declare class IO<E, A> {
|
|
|
755
913
|
* If this IO succeeds, the function is not called. The callback may be synchronous
|
|
756
914
|
* or asynchronous — the interpreter awaits if it returns a Promise.
|
|
757
915
|
*
|
|
758
|
-
* If the side-effect throws,
|
|
759
|
-
*
|
|
916
|
+
* If the side-effect throws or rejects, that is a **defect**, as a throw in `mapErr` is: it does
|
|
917
|
+
* not replace the error, and `unsafeRun()` rejects with it. For a side effect that may fail and
|
|
918
|
+
* whose failure should be ignored, catch it inside the callback.
|
|
760
919
|
*
|
|
761
920
|
* @param {(e: E) => void | Promise<void>} f The side-effect function.
|
|
762
921
|
* @returns {IO<E, A>} A new IO that performs the side-effect but preserves the original error.
|
|
@@ -871,12 +1030,26 @@ export declare class IO<E, A> {
|
|
|
871
1030
|
* exception from an effect or callback that was not declared fallible — with the original
|
|
872
1031
|
* exception, after cleanup has run; handle it with `.catch` at the edge of the program.
|
|
873
1032
|
*
|
|
1033
|
+
* With a `signal`, aborting it cancels the run as cancelling a fiber does: effects receive the
|
|
1034
|
+
* signal, an effect that ignores it is abandoned, finalizers and `bracket` releases run, forked
|
|
1035
|
+
* child fibers are cancelled, and the promise resolves with `Cancelled` once that is done. A
|
|
1036
|
+
* signal that has already aborted gives `Cancelled` without running anything.
|
|
1037
|
+
*
|
|
874
1038
|
* @returns {Promise<Err<E> | Ok<A>>} The result of the computation.
|
|
875
1039
|
*
|
|
876
1040
|
* @example
|
|
877
1041
|
* const result = await IO.of(42).unsafeRun();
|
|
878
1042
|
* // result: { type: "Ok", value: 42 }
|
|
1043
|
+
*
|
|
1044
|
+
* @example
|
|
1045
|
+
* // Stop the work when the client disconnects.
|
|
1046
|
+
* const exit = await handle(request).unsafeRun({ signal: request.signal });
|
|
1047
|
+
* if (exit.type === "Cancelled") return;
|
|
879
1048
|
*/
|
|
1049
|
+
/** Runs the IO under `signal`; aborting it cancels the run, which then ends as `Cancelled`. */
|
|
1050
|
+
unsafeRun(options: {
|
|
1051
|
+
readonly signal: AbortSignal;
|
|
1052
|
+
}): Promise<Exit<E, A>>;
|
|
880
1053
|
unsafeRun(): Promise<Err<E> | Ok<A>>;
|
|
881
1054
|
/**
|
|
882
1055
|
* Executes the IO and folds both outcomes (success and error) into a single type.
|
|
@@ -983,6 +1156,10 @@ export declare class IO<E, A> {
|
|
|
983
1156
|
* returned once the cancelled computation has unwound (its finalizers have run); an effect that
|
|
984
1157
|
* ignores the signal is abandoned rather than waited for.
|
|
985
1158
|
*
|
|
1159
|
+
* The deadline bounds waiting, not work: it fires on a timer, so work that never waits for the
|
|
1160
|
+
* next macrotask (a long synchronous loop, a large `traverse` of synchronous steps) runs to its
|
|
1161
|
+
* end before the timeout can take effect.
|
|
1162
|
+
*
|
|
986
1163
|
* This is a first-class replacement for the verbose `IO.race` workaround:
|
|
987
1164
|
* ```typescript
|
|
988
1165
|
* // Before — manual race
|
|
@@ -1030,27 +1207,38 @@ export declare class IO<E, A> {
|
|
|
1030
1207
|
*
|
|
1031
1208
|
* A defect in the fiber makes `join()` reject with it. If the fiber is never joined, the defect
|
|
1032
1209
|
* is reported as an unhandled rejection once the run that forked it has ended, or straight away
|
|
1033
|
-
* when it happens after that (a handle returned out of its run that nobody joins).
|
|
1210
|
+
* when it happens after that (a handle returned out of its run that nobody joins). With
|
|
1211
|
+
* `onDefect`, that defect goes to the handler instead, right after it happens.
|
|
1034
1212
|
*
|
|
1213
|
+
* @param options `onDefect`: receives the defect of a fiber nobody joins. See {@link ForkOptions}.
|
|
1035
1214
|
* @returns {IO<never, Fiber<E, A>>} An IO that, when executed, starts this IO and returns a Fiber.
|
|
1036
1215
|
*
|
|
1037
1216
|
* @example
|
|
1038
|
-
* const io = IO.forM<AppError, string>(async
|
|
1039
|
-
* const fiber = await
|
|
1217
|
+
* const io = IO.forM<AppError, string>(async ($) => {
|
|
1218
|
+
* const fiber = await $(longRunningTask.fork());
|
|
1040
1219
|
* // ... do other work ...
|
|
1041
1220
|
* const outcome = await fiber.join(); // Ok | Err | Cancelled
|
|
1042
1221
|
* return outcome.type === "Ok" ? outcome.value : "unavailable";
|
|
1043
1222
|
* });
|
|
1044
1223
|
*/
|
|
1045
|
-
fork(): IO<never, Fiber<E, A>>;
|
|
1224
|
+
fork(options?: ForkOptions): IO<never, Fiber<E, A>>;
|
|
1046
1225
|
/**
|
|
1047
1226
|
* Like {@link fork}, but the fiber is not a child of the run that forks it: cancelling that run
|
|
1048
1227
|
* does not cancel the fiber. Use it for work that must finish on its own (a flush, an audit
|
|
1049
1228
|
* write) regardless of what happens to the code that started it; cancel it through its handle.
|
|
1050
1229
|
*
|
|
1230
|
+
* A daemon often outlives the request that started it, so a defect in it has nobody to reach:
|
|
1231
|
+
* pass `onDefect` to log it instead of letting it become an unhandled rejection, which stops a
|
|
1232
|
+
* Node process by default. A daemon's `onDefect` is called right after the defect happens,
|
|
1233
|
+
* unless the fiber is joined before then, even while the run that forked it is still running.
|
|
1234
|
+
*
|
|
1235
|
+
* @param options `onDefect`: receives the defect of a fiber nobody joins. See {@link ForkOptions}.
|
|
1051
1236
|
* @returns {IO<never, Fiber<E, A>>} An IO that, when executed, starts this IO and returns a Fiber.
|
|
1237
|
+
*
|
|
1238
|
+
* @example
|
|
1239
|
+
* audit(event).forkDaemon({ onDefect: (cause) => logger.error("audit write failed", cause) });
|
|
1052
1240
|
*/
|
|
1053
|
-
forkDaemon(): IO<never, Fiber<E, A>>;
|
|
1241
|
+
forkDaemon(options?: ForkOptions): IO<never, Fiber<E, A>>;
|
|
1054
1242
|
/**
|
|
1055
1243
|
* Applicative combine of independent IOs ("applicative for"). The IOs do not depend on one
|
|
1056
1244
|
* another, so they run concurrently via `Promise.all`, and — unlike the monadic {@link forM},
|
|
@@ -1100,13 +1288,13 @@ export declare class IO<E, A> {
|
|
|
1100
1288
|
static race<E, A>(...ops: IO<E, A>[]): IO<NonEmptyList<E>, A>;
|
|
1101
1289
|
/**
|
|
1102
1290
|
* Monadic for-comprehension ("monadic for"). Sequences dependent IO operations using an
|
|
1103
|
-
* imperative-style
|
|
1291
|
+
* imperative-style `$` function that unwraps IO values or short-circuits on the first
|
|
1104
1292
|
* error. This is the sequential, fail-fast counterpart to the applicative {@link forA}
|
|
1105
1293
|
* (which runs independent IOs in parallel and accumulates all errors).
|
|
1106
1294
|
*
|
|
1107
|
-
* Inside the `operation` callback, call
|
|
1295
|
+
* Inside the `operation` callback, call `$(io)` to execute an IO and extract its
|
|
1108
1296
|
* success value. If any bound IO fails, the whole comprehension short-circuits with that
|
|
1109
|
-
* error — subsequent
|
|
1297
|
+
* error — subsequent `$` calls are not executed.
|
|
1110
1298
|
*
|
|
1111
1299
|
* Uses an `IOEscape` sentinel internally to preserve the typed error `E` through
|
|
1112
1300
|
* JavaScript's throw/catch mechanism, ensuring the error channel remains type-safe.
|
|
@@ -1117,19 +1305,19 @@ export declare class IO<E, A> {
|
|
|
1117
1305
|
*
|
|
1118
1306
|
* @template E The error type shared by all bound IO operations.
|
|
1119
1307
|
* @template A The final success type produced by the comprehension.
|
|
1120
|
-
* @param {(
|
|
1121
|
-
* An async function that receives a
|
|
1308
|
+
* @param {($: <B>(effect: IO<E, B>) => Promise<B>) => Promise<A>} operation
|
|
1309
|
+
* An async function that receives a `$` callback for unwrapping IO values.
|
|
1122
1310
|
* @param {(e: unknown) => E} [liftE] Optional function to transform non-IO exceptions into E.
|
|
1123
1311
|
* @returns {IO<E, A>} An IO that, when executed, runs the comprehension.
|
|
1124
1312
|
*
|
|
1125
1313
|
* @example
|
|
1126
|
-
* const io = IO.forM<AppError, number>(async
|
|
1127
|
-
* const user = await
|
|
1128
|
-
* const orders = await
|
|
1314
|
+
* const io = IO.forM<AppError, number>(async ($) => {
|
|
1315
|
+
* const user = await $(fetchUser(userId));
|
|
1316
|
+
* const orders = await $(fetchOrders(user.id));
|
|
1129
1317
|
* return orders.length;
|
|
1130
1318
|
* });
|
|
1131
1319
|
*/
|
|
1132
|
-
static forM<E, A>(operation: (
|
|
1320
|
+
static forM<E, A>(operation: ($: <B>(effect: IO<E, B>) => Promise<B>) => Promise<A>, liftE?: (e: unknown) => E): IO<E, A>;
|
|
1133
1321
|
/**
|
|
1134
1322
|
* Sequentially executes a function over each item, collecting results into an array.
|
|
1135
1323
|
* Fail-fast: if any invocation fails, the remaining items are not processed and the
|
|
@@ -1153,18 +1341,28 @@ export declare class IO<E, A> {
|
|
|
1153
1341
|
* are collected into a `NonEmptyList`. Results, and errors, keep the order of
|
|
1154
1342
|
* `items`, not the order of completion.
|
|
1155
1343
|
*
|
|
1344
|
+
* With `concurrency: n`, at most `n` items run at once; the next item starts as soon as one
|
|
1345
|
+
* ends. Every item still runs, so every error is still collected. After a defect, or once the
|
|
1346
|
+
* run is cancelled, no further item starts. A `concurrency` that is not a positive integer or
|
|
1347
|
+
* `Infinity` throws `RangeError` where the call is written.
|
|
1348
|
+
*
|
|
1156
1349
|
* @template E The error type.
|
|
1157
1350
|
* @template A The input item type.
|
|
1158
1351
|
* @template B The output type for each item.
|
|
1159
1352
|
* @param {A[]} items The items to traverse in parallel.
|
|
1160
1353
|
* @param {(a: A) => IO<E, B>} f A function that produces an IO for each item.
|
|
1354
|
+
* @param options `concurrency`: how many items run at once (default `Infinity`).
|
|
1161
1355
|
* @returns {IO<NonEmptyList<E>, List<B>>} An IO that succeeds with all results as a List, or fails with all errors.
|
|
1162
1356
|
*
|
|
1163
1357
|
* @example
|
|
1164
1358
|
* const io = IO.parTraverse([1, 2, 3], n => IO.of(n * 2));
|
|
1165
1359
|
* // result: { type: "Ok", value: List [2, 4, 6] }
|
|
1360
|
+
*
|
|
1361
|
+
* @example
|
|
1362
|
+
* // At most 5 queries at once, however many ids the request carries.
|
|
1363
|
+
* const users = IO.parTraverse(ids, (id) => findUser(id), { concurrency: 5 });
|
|
1166
1364
|
*/
|
|
1167
|
-
static parTraverse<E, A, B>(items: readonly A[], f: (a: A) => IO<E, B
|
|
1365
|
+
static parTraverse<E, A, B>(items: readonly A[], f: (a: A) => IO<E, B>, options?: Concurrency): IO<NonEmptyList<E>, List<B>>;
|
|
1168
1366
|
/**
|
|
1169
1367
|
* Sequentially executes an array of IOs, collecting results into an array.
|
|
1170
1368
|
* Equivalent to `traverse(ios, x => x)`. Fail-fast on the first error.
|
|
@@ -1181,18 +1379,19 @@ export declare class IO<E, A> {
|
|
|
1181
1379
|
static sequence<E, A>(ios: readonly IO<E, A>[]): IO<E, List<A>>;
|
|
1182
1380
|
/**
|
|
1183
1381
|
* Executes an array of IOs in parallel, collecting all results or all errors.
|
|
1184
|
-
* Equivalent to `parTraverse(ios, x => x)`. Results and errors keep the order of `ios`.
|
|
1382
|
+
* Equivalent to `parTraverse(ios, x => x, options)`. Results and errors keep the order of `ios`.
|
|
1185
1383
|
*
|
|
1186
1384
|
* @template E The error type.
|
|
1187
1385
|
* @template A The success type of each IO.
|
|
1188
1386
|
* @param {IO<E, A>[]} ios The IO operations to execute in parallel.
|
|
1387
|
+
* @param options `concurrency`: how many IOs run at once (default `Infinity`); see {@link parTraverse}.
|
|
1189
1388
|
* @returns {IO<NonEmptyList<E>, List<A>>} An IO that succeeds with all results as a List, or fails with all errors.
|
|
1190
1389
|
*
|
|
1191
1390
|
* @example
|
|
1192
1391
|
* const io = IO.parSequence([IO.of(1), IO.of(2), IO.of(3)]);
|
|
1193
1392
|
* // result: { type: "Ok", value: List [1, 2, 3] }
|
|
1194
1393
|
*/
|
|
1195
|
-
static parSequence<E, A>(ios: readonly IO<E, A>[]): IO<NonEmptyList<E>, List<A>>;
|
|
1394
|
+
static parSequence<E, A>(ios: readonly IO<E, A>[], options?: Concurrency): IO<NonEmptyList<E>, List<A>>;
|
|
1196
1395
|
}
|
|
1197
1396
|
|
|
1198
1397
|
export declare class Left<A> extends Either<A, never> {
|
|
@@ -1293,7 +1492,7 @@ export declare class List<A> {
|
|
|
1293
1492
|
* @param {number} endExclusive The exclusive end value.
|
|
1294
1493
|
* @param {number} [step=1] The increment between successive values. Must be non-zero.
|
|
1295
1494
|
* @returns {List<number>} A `List<number>` of the requested range.
|
|
1296
|
-
* @throws {
|
|
1495
|
+
* @throws {RangeError} If `step` is zero, an argument is not finite, or the range would hold more than 2^32 − 1 elements.
|
|
1297
1496
|
*
|
|
1298
1497
|
* @example
|
|
1299
1498
|
* List.range(0, 5).toArray(); // [0, 1, 2, 3, 4]
|
|
@@ -2694,6 +2893,14 @@ export declare class NonEmptyList<A> {
|
|
|
2694
2893
|
toJSON(): A[];
|
|
2695
2894
|
}
|
|
2696
2895
|
|
|
2896
|
+
/**
|
|
2897
|
+
* A body result that is not a promise: an `async` body would return before its `$` calls ran, so
|
|
2898
|
+
* `forM` rejects it at compile time (and with a `TypeError` at run time).
|
|
2899
|
+
*/
|
|
2900
|
+
declare type NotThenable = {
|
|
2901
|
+
readonly then?: never;
|
|
2902
|
+
} | null | undefined;
|
|
2903
|
+
|
|
2697
2904
|
export declare interface Ok<A> {
|
|
2698
2905
|
readonly type: "Ok";
|
|
2699
2906
|
readonly value: A;
|
|
@@ -2812,6 +3019,40 @@ export declare abstract class Option<A> {
|
|
|
2812
3019
|
* Option.empty<number>().tapNone(() => console.log("No value")); // Logs "No value"
|
|
2813
3020
|
*/
|
|
2814
3021
|
abstract tapNone(f: () => void): Option<A>;
|
|
3022
|
+
/**
|
|
3023
|
+
* Applicative combine of independent `Option`s ("applicative for"): `Some` of the last
|
|
3024
|
+
* argument applied to their values (in argument order) when all are `Some`, and `None` as soon
|
|
3025
|
+
* as one is `None` — the combiner is then not called. A `None` carries nothing, so unlike
|
|
3026
|
+
* `Either.forA` there is nothing to collect. A combiner result of `null` or `undefined` is `None`.
|
|
3027
|
+
*
|
|
3028
|
+
* @example
|
|
3029
|
+
* const contact = Option.forA(name, email, (n, e) => ({ name: n, email: e })); // Option<{ name, email }>
|
|
3030
|
+
*/
|
|
3031
|
+
static forA<A1, A2, R>(o1: Option<A1>, o2: Option<A2>, f: (a1: A1, a2: A2) => R | null | undefined): Option<NonNullable<R>>;
|
|
3032
|
+
static forA<A1, A2, A3, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, f: (a1: A1, a2: A2, a3: A3) => R | null | undefined): Option<NonNullable<R>>;
|
|
3033
|
+
static forA<A1, A2, A3, A4, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, f: (a1: A1, a2: A2, a3: A3, a4: A4) => R | null | undefined): Option<NonNullable<R>>;
|
|
3034
|
+
static forA<A1, A2, A3, A4, A5, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, o5: Option<A5>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => R | null | undefined): Option<NonNullable<R>>;
|
|
3035
|
+
static forA<A1, A2, A3, A4, A5, A6, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, o5: Option<A5>, o6: Option<A6>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => R | null | undefined): Option<NonNullable<R>>;
|
|
3036
|
+
static forA<A1, A2, A3, A4, A5, A6, A7, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, o5: Option<A5>, o6: Option<A6>, o7: Option<A7>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => R | null | undefined): Option<NonNullable<R>>;
|
|
3037
|
+
static forA<A1, A2, A3, A4, A5, A6, A7, A8, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, o5: Option<A5>, o6: Option<A6>, o7: Option<A7>, o8: Option<A8>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8) => R | null | undefined): Option<NonNullable<R>>;
|
|
3038
|
+
static forA<A1, A2, A3, A4, A5, A6, A7, A8, A9, R>(o1: Option<A1>, o2: Option<A2>, o3: Option<A3>, o4: Option<A4>, o5: Option<A5>, o6: Option<A6>, o7: Option<A7>, o8: Option<A8>, o9: Option<A9>, f: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7, a8: A8, a9: A9) => R | null | undefined): Option<NonNullable<R>>;
|
|
3039
|
+
/**
|
|
3040
|
+
* Monadic comprehension ("monadic for") over `Option`, synchronous. Inside `operation`,
|
|
3041
|
+
* `$(option)` returns the `Some` value; the first `None` stops the body, and `forM` returns
|
|
3042
|
+
* `None`. The body's return value becomes the result, `None` when it is `null` or `undefined`.
|
|
3043
|
+
* An exception is not caught: it propagates from `forM`.
|
|
3044
|
+
*
|
|
3045
|
+
* `$` stops the body by throwing, so a `try` / `catch` in the body must rethrow what it does
|
|
3046
|
+
* not handle, and the body must be synchronous.
|
|
3047
|
+
*
|
|
3048
|
+
* @example
|
|
3049
|
+
* const city = Option.forM(($) => {
|
|
3050
|
+
* const user = $(findUser(id));
|
|
3051
|
+
* const address = $(user.address);
|
|
3052
|
+
* return address.city;
|
|
3053
|
+
* }); // Option<string>
|
|
3054
|
+
*/
|
|
3055
|
+
static forM<A>(operation: ($: <B>(option: Option<B>) => B) => A & NotThenable): Option<NonNullable<A>>;
|
|
2815
3056
|
/**
|
|
2816
3057
|
* Applies one of two provided functions based on the contents of this `Option`.
|
|
2817
3058
|
* If it is `None`, it applies `ifNone`. If it is `Some`, it applies `ifSome`.
|
|
@@ -3497,14 +3738,14 @@ export declare type Pipe<E, A, B> = (stream: Stream<E, A>) => Stream<E, B>;
|
|
|
3497
3738
|
*
|
|
3498
3739
|
* @example
|
|
3499
3740
|
* // Turn an EventEmitter into a Stream
|
|
3500
|
-
* const program = IO.forM<never, void>(async (
|
|
3501
|
-
* const queue = await
|
|
3741
|
+
* const program = IO.forM<never, void>(async ($) => {
|
|
3742
|
+
* const queue = await $(Queue.bounded<Message>(1024, OverflowStrategy.DropOldest));
|
|
3502
3743
|
* emitter.on("message", (m) => queue.unsafeOffer(m));
|
|
3503
3744
|
* emitter.once("close", () => queue.unsafeClose());
|
|
3504
|
-
* await
|
|
3745
|
+
* await $(Stream.from(queue).runForEach((m) => handle(m)));
|
|
3505
3746
|
* });
|
|
3506
3747
|
*/
|
|
3507
|
-
export declare class Queue<A> {
|
|
3748
|
+
export declare class Queue<in out A> {
|
|
3508
3749
|
private readonly capacity;
|
|
3509
3750
|
private readonly onOverflow;
|
|
3510
3751
|
private readonly items;
|
|
@@ -3571,7 +3812,8 @@ export declare class Queue<A> {
|
|
|
3571
3812
|
* Offers a value. Resolves `true` when the value was accepted with nothing lost, `false` when
|
|
3572
3813
|
* it was refused (queue closed, or `DropNewest` at capacity) or an older value was evicted
|
|
3573
3814
|
* (`DropOldest` at capacity). Under `Suspend`, an offer at capacity waits for a `take`;
|
|
3574
|
-
* cancelling the waiting fiber withdraws the offer
|
|
3815
|
+
* cancelling the waiting fiber withdraws the offer, unless a `take` accepted the value at the
|
|
3816
|
+
* same moment: the run then ends `Cancelled` with the value in the queue all the same.
|
|
3575
3817
|
*
|
|
3576
3818
|
* @param {A} value The value to enqueue.
|
|
3577
3819
|
* @returns {IO<never, boolean>}
|
|
@@ -3598,6 +3840,8 @@ export declare class Queue<A> {
|
|
|
3598
3840
|
* if (next.type === "Ok" && !next.value.done) handle(next.value.value);
|
|
3599
3841
|
*/
|
|
3600
3842
|
take(): IO<never, IteratorResult<A, void>>;
|
|
3843
|
+
/** Returns a value a cancelled taker received: to the next waiting taker, else to the front. */
|
|
3844
|
+
private putBack;
|
|
3601
3845
|
/**
|
|
3602
3846
|
* Closes the queue: every waiting `take` resumes with `{ done: true }`, every waiting `offer` resumes
|
|
3603
3847
|
* with `false`, and later offers are refused. Values already buffered stay available to `take`.
|
|
@@ -3658,8 +3902,8 @@ export declare class Queue<A> {
|
|
|
3658
3902
|
* const data = await fetchData.run({ multiplier: 1, apiEndpoint: 'https://api.example.com' });
|
|
3659
3903
|
* ```
|
|
3660
3904
|
*/
|
|
3661
|
-
export declare class Reader<R, A> {
|
|
3662
|
-
private f;
|
|
3905
|
+
export declare class Reader<in R, out A> {
|
|
3906
|
+
private readonly f;
|
|
3663
3907
|
/**
|
|
3664
3908
|
* Initializes a new `Reader` instance.
|
|
3665
3909
|
*
|
|
@@ -3734,6 +3978,10 @@ export declare class Reader<R, A> {
|
|
|
3734
3978
|
* computation can determine the next computation. It is useful for creating complex
|
|
3735
3979
|
* workflows that depend on the environment and previous results.
|
|
3736
3980
|
*
|
|
3981
|
+
* The chain needs every environment its steps read: a `Reader<{ db: Db }, A>` chained with a
|
|
3982
|
+
* step that reads `{ cache: Cache }` is a `Reader<{ db: Db } & { cache: Cache }, B>`. A step
|
|
3983
|
+
* that reads the same environment, or none, keeps it.
|
|
3984
|
+
*
|
|
3737
3985
|
* @param f - A function that takes the result of the current `Reader` and returns a new `Reader`.
|
|
3738
3986
|
* @returns A new `Reader` instance that represents the chained computation.
|
|
3739
3987
|
*
|
|
@@ -3750,6 +3998,8 @@ export declare class Reader<R, A> {
|
|
|
3750
3998
|
* // Running the Reader with an environment will fetch and process the data
|
|
3751
3999
|
* processData.run({ apiEndpoint: 'https://api.example.com' }).then(console.log);
|
|
3752
4000
|
*/
|
|
4001
|
+
flatMap<R2, B>(f: (a: A) => Reader<R2, B>): Reader<R & R2, B>;
|
|
4002
|
+
/** Chains a Reader that reads the same environment (explicit type argument `<B>`). */
|
|
3753
4003
|
flatMap<B>(f: (a: A) => Reader<R, B>): Reader<R, B>;
|
|
3754
4004
|
/**
|
|
3755
4005
|
* Creates a `Reader` instance that provides access to the environment.
|
|
@@ -3781,6 +4031,10 @@ export declare class Reader<R, A> {
|
|
|
3781
4031
|
* environment and collecting their results into a single value. It is purely
|
|
3782
4032
|
* sequential — a `Reader` performs no concurrency.
|
|
3783
4033
|
*
|
|
4034
|
+
* The combined `Reader` needs every environment its parts read: zipping a
|
|
4035
|
+
* `Reader<{ db: Db }, A>` with a `Reader<{ cache: Cache }, B>` gives a
|
|
4036
|
+
* `Reader<{ db: Db } & { cache: Cache }, readonly [A, B]>`.
|
|
4037
|
+
*
|
|
3784
4038
|
* @param readers - An array of `Reader` instances to be combined.
|
|
3785
4039
|
* @returns A new `Reader` instance that returns a tuple of the results of the given `Reader` instances.
|
|
3786
4040
|
*
|
|
@@ -3797,6 +4051,10 @@ export declare class Reader<R, A> {
|
|
|
3797
4051
|
* const env = { valueA: 42, valueB: "hello", valueC: true };
|
|
3798
4052
|
* console.log(combinedReader.run(env)); // [42, "hello", true]
|
|
3799
4053
|
*/
|
|
4054
|
+
static zip<const T extends readonly Reader<never, unknown>[]>(...readers: T): Reader<ReaderEnvs<T>, {
|
|
4055
|
+
[K in keyof T]: ReaderValue<T[K]>;
|
|
4056
|
+
}>;
|
|
4057
|
+
/** Combines Readers that share an environment (explicit type arguments `<R, A>`). */
|
|
3800
4058
|
static zip<R, const A extends readonly unknown[]>(...readers: {
|
|
3801
4059
|
[K in keyof A]: Reader<R, A[K]>;
|
|
3802
4060
|
}): Reader<R, A>;
|
|
@@ -3861,6 +4119,18 @@ export declare class Reader<R, A> {
|
|
|
3861
4119
|
run(env: R): A;
|
|
3862
4120
|
}
|
|
3863
4121
|
|
|
4122
|
+
/** The environment a Reader reads. */
|
|
4123
|
+
declare type ReaderEnv<T> = T extends Reader<infer R, unknown> ? R : never;
|
|
4124
|
+
|
|
4125
|
+
/**
|
|
4126
|
+
* The environment that every Reader of a tuple reads: the intersection of their environments. A
|
|
4127
|
+
* plain array (not a tuple) gives the environment of its element type.
|
|
4128
|
+
*/
|
|
4129
|
+
declare type ReaderEnvs<T extends readonly unknown[]> = T extends readonly [] ? unknown : T extends readonly [infer Head, ...infer Rest] ? ReaderEnv<Head> & ReaderEnvs<Rest> : ReaderEnv<T[number]>;
|
|
4130
|
+
|
|
4131
|
+
/** The value a Reader produces. */
|
|
4132
|
+
declare type ReaderValue<T> = T extends Reader<never, infer A> ? A : never;
|
|
4133
|
+
|
|
3864
4134
|
/**
|
|
3865
4135
|
* A mutable cell whose every operation is an `IO<never, _>`. `Ref` is how state lives *inside* an
|
|
3866
4136
|
* `IO` program — a session, a cache, a counter — instead of in a closure variable the effect
|
|
@@ -3880,15 +4150,15 @@ export declare class Reader<R, A> {
|
|
|
3880
4150
|
* @typeParam A The type of the value held in the cell.
|
|
3881
4151
|
*
|
|
3882
4152
|
* @example
|
|
3883
|
-
* const program = IO.forM<never, number>(async (
|
|
3884
|
-
* const counter = await
|
|
3885
|
-
* await
|
|
3886
|
-
* await
|
|
3887
|
-
* return
|
|
4153
|
+
* const program = IO.forM<never, number>(async ($) => {
|
|
4154
|
+
* const counter = await $(Ref.of(0));
|
|
4155
|
+
* await $(counter.update((n) => n + 1));
|
|
4156
|
+
* await $(counter.update((n) => n + 1));
|
|
4157
|
+
* return $(counter.get());
|
|
3888
4158
|
* });
|
|
3889
4159
|
* await program.unsafeRun(); // { type: "Ok", value: 2 }
|
|
3890
4160
|
*/
|
|
3891
|
-
export declare class Ref<A> {
|
|
4161
|
+
export declare class Ref<in out A> {
|
|
3892
4162
|
private value;
|
|
3893
4163
|
private constructor();
|
|
3894
4164
|
/**
|
|
@@ -3969,6 +4239,212 @@ export declare class Ref<A> {
|
|
|
3969
4239
|
getAndSet(value: A): IO<never, A>;
|
|
3970
4240
|
}
|
|
3971
4241
|
|
|
4242
|
+
/** How the `use` step of a `bracket` ended, as its release receives it. */
|
|
4243
|
+
export declare type ReleaseExit<E, A> = Exit<E, A> | Defect;
|
|
4244
|
+
|
|
4245
|
+
/**
|
|
4246
|
+
* A resource that opens with an effect and closes with another: a database pool, an HTTP server, a
|
|
4247
|
+
* worker queue. A `Resource` is a description, like an {@link IO}: nothing opens until {@link use}
|
|
4248
|
+
* runs, and each `use` opens its own copy.
|
|
4249
|
+
*
|
|
4250
|
+
* Resources compose with {@link flatMap}, {@link zip} and {@link forM}. `use` opens them in order,
|
|
4251
|
+
* runs its body, and then closes them in reverse order, whatever happened: success, failure, defect
|
|
4252
|
+
* or cancellation. Each open stays next to its close, and the close order follows from the open
|
|
4253
|
+
* order.
|
|
4254
|
+
*
|
|
4255
|
+
* For one resource used inside one step, {@link IO.bracket} is enough. A `Resource` is for several
|
|
4256
|
+
* resources that live as long as a process.
|
|
4257
|
+
*
|
|
4258
|
+
* @typeParam E The error type of opening.
|
|
4259
|
+
* @typeParam A The value the resource gives to its use.
|
|
4260
|
+
*
|
|
4261
|
+
* @example
|
|
4262
|
+
* const server = Resource.forM<StartFailure, RunningServer>(async ($) => {
|
|
4263
|
+
* const db = await $(Resource.make(openPool(config), (pool) => closePool(pool)));
|
|
4264
|
+
* const http = await $(Resource.make(listen(db), (server) => stopListening(server)));
|
|
4265
|
+
* return { db, http };
|
|
4266
|
+
* });
|
|
4267
|
+
*
|
|
4268
|
+
* // Closes the HTTP server first, then the pool.
|
|
4269
|
+
* await server.use(() => untilSignal).unsafeRun();
|
|
4270
|
+
*/
|
|
4271
|
+
export declare class Resource<E, A> {
|
|
4272
|
+
private readonly open;
|
|
4273
|
+
/** Build a `Resource` through its static constructors: `Resource.make`, `Resource.of`, `Resource.eval`. */
|
|
4274
|
+
private constructor();
|
|
4275
|
+
/**
|
|
4276
|
+
* A resource that opens with `acquire` and closes with `release`. `release` learns how the use
|
|
4277
|
+
* ended: `Ok` with the use's value, `Err` with its error, `Cancelled`, or `Defect`. When a later
|
|
4278
|
+
* resource fails to open, `release` receives that `Err`.
|
|
4279
|
+
*
|
|
4280
|
+
* `acquire` runs masked, as in {@link IO.bracket}. If the use is cancelled while `acquire` runs,
|
|
4281
|
+
* the use ends as `Cancelled` at once, and a value `acquire` still produces later is released as
|
|
4282
|
+
* soon as it arrives, with `Cancelled`.
|
|
4283
|
+
*
|
|
4284
|
+
* `release` runs to its end, without the abort signal. A release that never ends holds the use for
|
|
4285
|
+
* ever, even under `timeout`, so a release that may hang bounds its own time with `timeout`.
|
|
4286
|
+
*
|
|
4287
|
+
* If `release` fails (throws, even before it returns its `IO`, or rejects) after a successful use,
|
|
4288
|
+
* the use fails with that failure as a defect. After a failed, defective or cancelled use, and for a
|
|
4289
|
+
* value released after it arrived late, the failure is dropped and leaves no trace: a release whose
|
|
4290
|
+
* failure matters handles it itself, for example by logging it.
|
|
4291
|
+
*
|
|
4292
|
+
* @template E The error type of `acquire`.
|
|
4293
|
+
* @template A The value `acquire` produces.
|
|
4294
|
+
* @param {IO<E, A>} acquire Opens the resource.
|
|
4295
|
+
* @param {(a: A, exit: ReleaseExit<unknown, unknown>) => IO<never, void>} release Closes the
|
|
4296
|
+
* resource. Must not fail.
|
|
4297
|
+
* @returns {Resource<E, A>}
|
|
4298
|
+
*
|
|
4299
|
+
* @example
|
|
4300
|
+
* const pool = Resource.make(
|
|
4301
|
+
* IO.lift(() => createPool(config), toDbError),
|
|
4302
|
+
* (pool) => IO.promise(() => pool.end())
|
|
4303
|
+
* );
|
|
4304
|
+
*/
|
|
4305
|
+
static make<E, A>(acquire: IO<E, A>, release: (a: A, exit: ReleaseExit<unknown, unknown>) => IO<never, void>): Resource<E, A>;
|
|
4306
|
+
/**
|
|
4307
|
+
* A step with nothing to open, whose `release` runs when the use ends, in its place in the reverse
|
|
4308
|
+
* order. `release` learns how the use ended and follows the rules of a {@link make} release. Use it
|
|
4309
|
+
* for a shutdown step that only closes, such as draining work that exists from the start.
|
|
4310
|
+
*
|
|
4311
|
+
* @param {(exit: ReleaseExit<unknown, unknown>) => IO<never, void>} release Runs when the use ends.
|
|
4312
|
+
* Must not fail.
|
|
4313
|
+
* @returns {Resource<never, void>}
|
|
4314
|
+
*
|
|
4315
|
+
* @example
|
|
4316
|
+
* await $(Resource.onClose(() => IO.promise(() => work.drain()))); // after serving stops, before the pool closes
|
|
4317
|
+
*/
|
|
4318
|
+
static onClose(release: (exit: ReleaseExit<unknown, unknown>) => IO<never, void>): Resource<never, void>;
|
|
4319
|
+
/**
|
|
4320
|
+
* A plain value, with nothing to close.
|
|
4321
|
+
*
|
|
4322
|
+
* @template A The type of the value.
|
|
4323
|
+
* @param {A} value The value.
|
|
4324
|
+
* @returns {Resource<never, A>}
|
|
4325
|
+
*
|
|
4326
|
+
* @example
|
|
4327
|
+
* const config = Resource.of({ port: 8080 });
|
|
4328
|
+
*/
|
|
4329
|
+
static of<A>(value: A): Resource<never, A>;
|
|
4330
|
+
/**
|
|
4331
|
+
* An effect with nothing to close. It runs each time the resource is used, not when it is built.
|
|
4332
|
+
*
|
|
4333
|
+
* @template E The error type of `io`.
|
|
4334
|
+
* @template A The success type of `io`.
|
|
4335
|
+
* @param {IO<E, A>} io The effect.
|
|
4336
|
+
* @returns {Resource<E, A>}
|
|
4337
|
+
*
|
|
4338
|
+
* @example
|
|
4339
|
+
* const app = Resource.eval(IO.sync(() => App.create(options)));
|
|
4340
|
+
*/
|
|
4341
|
+
static eval<E, A>(io: IO<E, A>): Resource<E, A>;
|
|
4342
|
+
/**
|
|
4343
|
+
* Combines independent resources into one that gives a tuple of their values. They open in the
|
|
4344
|
+
* order given and close in reverse order. When one fails to open, the ones already open close.
|
|
4345
|
+
*
|
|
4346
|
+
* @template T The resources, as a tuple.
|
|
4347
|
+
* @param {T} resources The resources to combine.
|
|
4348
|
+
* @returns A resource whose error is the union of their errors, and whose value is the tuple of
|
|
4349
|
+
* their values.
|
|
4350
|
+
*
|
|
4351
|
+
* @example
|
|
4352
|
+
* const both = Resource.zip(pool, cache); // Resource<DbError | CacheError, readonly [Pool, Cache]>
|
|
4353
|
+
* await both.use(([pool, cache]) => serve(pool, cache)).unsafeRun();
|
|
4354
|
+
*/
|
|
4355
|
+
static zip<const T extends readonly Resource<any, any>[]>(...resources: T): Resource<ResourceError<T[number]>, {
|
|
4356
|
+
[K in keyof T]: ResourceValue<T[K]>;
|
|
4357
|
+
}>;
|
|
4358
|
+
/**
|
|
4359
|
+
* Monadic for-comprehension, like {@link IO.forM}. Each `$(resource)` call opens a resource and
|
|
4360
|
+
* returns its value; the resource stays open until the use ends. Resources close in reverse order
|
|
4361
|
+
* of the `$` calls. When one fails to open, the comprehension stops with its error, and the ones
|
|
4362
|
+
* already open close.
|
|
4363
|
+
*
|
|
4364
|
+
* `$` takes a `Resource` only, so each step says whether it opens something that closes. A step
|
|
4365
|
+
* with nothing to close is `$(Resource.eval(io))`. Await every `$` call: one the body does not
|
|
4366
|
+
* await opens in an order nobody chose.
|
|
4367
|
+
*
|
|
4368
|
+
* When `liftE` is provided, exceptions thrown inside the body become errors of type `E`. Without
|
|
4369
|
+
* `liftE` such an exception is a defect.
|
|
4370
|
+
*
|
|
4371
|
+
* @template E The error type shared by all opened resources.
|
|
4372
|
+
* @template A The value the comprehension gives to its use.
|
|
4373
|
+
* @param {($: <B>(resource: Resource<E, B>) => Promise<B>) => Promise<A>} body An async function
|
|
4374
|
+
* that receives a `$` callback for opening resources.
|
|
4375
|
+
* @param {(e: unknown) => E} [liftE] Optional function to turn exceptions into E.
|
|
4376
|
+
* @returns {Resource<E, A>}
|
|
4377
|
+
*
|
|
4378
|
+
* @example
|
|
4379
|
+
* const server = Resource.forM<StartFailure, RunningServer>(async ($) => {
|
|
4380
|
+
* const app = await $(Resource.eval(IO.sync(() => App.create(options)))); // nothing to close
|
|
4381
|
+
* const account = await $(Resource.make(startAccount(app), (a) => a.close));
|
|
4382
|
+
* await $(Resource.make(listen(app), () => App.close(app))); // closed first
|
|
4383
|
+
* return { app, account };
|
|
4384
|
+
* });
|
|
4385
|
+
*/
|
|
4386
|
+
static forM<E, A>(body: ($: <B>(resource: Resource<E, B>) => Promise<B>) => Promise<A>, liftE?: (e: unknown) => E): Resource<E, A>;
|
|
4387
|
+
/**
|
|
4388
|
+
* Opens the resource, runs `f` with its value, and then closes everything it opened, in reverse
|
|
4389
|
+
* order. The closes run after a success, a failure, a defect and a cancellation alike, to their end
|
|
4390
|
+
* and without the abort signal.
|
|
4391
|
+
*
|
|
4392
|
+
* - A failing release after a successful `f` makes the use fail with a defect.
|
|
4393
|
+
* - After a failed, defective or cancelled `f`, a failing release is dropped and `f`'s outcome is
|
|
4394
|
+
* kept.
|
|
4395
|
+
*
|
|
4396
|
+
* @template F The error type of `f`.
|
|
4397
|
+
* @template B The success type of `f`.
|
|
4398
|
+
* @param {(a: A) => IO<F, B>} f Uses the resource.
|
|
4399
|
+
* @returns {IO<E | F, B>} An IO that opens, uses and closes.
|
|
4400
|
+
*
|
|
4401
|
+
* @example
|
|
4402
|
+
* const count = pool.use((pool) => IO.lift(() => pool.query("SELECT count(*) FROM users"), toDbError));
|
|
4403
|
+
*/
|
|
4404
|
+
use<F, B>(f: (a: A) => IO<F, B>): IO<E | F, B>;
|
|
4405
|
+
/**
|
|
4406
|
+
* Transforms the value. The release is unchanged.
|
|
4407
|
+
*
|
|
4408
|
+
* @template B The new value type.
|
|
4409
|
+
* @param {(a: A) => B} f The transformation.
|
|
4410
|
+
* @returns {Resource<E, B>}
|
|
4411
|
+
*
|
|
4412
|
+
* @example
|
|
4413
|
+
* const users = pool.map((pool) => new UserRepository(pool));
|
|
4414
|
+
*/
|
|
4415
|
+
map<B>(f: (a: A) => B): Resource<E, B>;
|
|
4416
|
+
/**
|
|
4417
|
+
* Opens a second resource that may depend on the value of the first. The second closes before the
|
|
4418
|
+
* first.
|
|
4419
|
+
*
|
|
4420
|
+
* @template F The error type of the second resource.
|
|
4421
|
+
* @template B The value type of the second resource.
|
|
4422
|
+
* @param {(a: A) => Resource<F, B>} f Builds the second resource from the first value.
|
|
4423
|
+
* @returns {Resource<E | F, B>}
|
|
4424
|
+
*
|
|
4425
|
+
* @example
|
|
4426
|
+
* const server = pool.flatMap((pool) => Resource.make(listen(pool), (server) => server.stop()));
|
|
4427
|
+
*/
|
|
4428
|
+
flatMap<F, B>(f: (a: A) => Resource<F, B>): Resource<E | F, B>;
|
|
4429
|
+
/**
|
|
4430
|
+
* Transforms the error of opening. The error of the body given to {@link use} is not changed.
|
|
4431
|
+
*
|
|
4432
|
+
* @template F The new error type.
|
|
4433
|
+
* @param {(e: E) => F} f The transformation.
|
|
4434
|
+
* @returns {Resource<F, A>}
|
|
4435
|
+
*
|
|
4436
|
+
* @example
|
|
4437
|
+
* const pool = Resource.make(openPool(config), closePool).mapErr((e) => new StartFailure("db", e));
|
|
4438
|
+
*/
|
|
4439
|
+
mapErr<F>(f: (e: E) => F): Resource<F, A>;
|
|
4440
|
+
}
|
|
4441
|
+
|
|
4442
|
+
/** The error type of a resource; distributes over a union of resources. */
|
|
4443
|
+
declare type ResourceError<R> = R extends Resource<infer E, any> ? E : never;
|
|
4444
|
+
|
|
4445
|
+
/** The value type of a resource. */
|
|
4446
|
+
declare type ResourceValue<R> = R extends Resource<any, infer A> ? A : never;
|
|
4447
|
+
|
|
3972
4448
|
export declare class Right<B> extends Either<never, B> {
|
|
3973
4449
|
readonly value: B;
|
|
3974
4450
|
readonly type: "Right";
|
|
@@ -4178,7 +4654,7 @@ export declare class Stream<E, A> {
|
|
|
4178
4654
|
* (conn) => IO.promise(() => conn.close())
|
|
4179
4655
|
* );
|
|
4180
4656
|
*/
|
|
4181
|
-
static bracket<E, F, R, A>(acquire: IO<E, R>, use: (r: R) => Stream<F, A>, release: (r: R) => IO<never, void>): Stream<E | F, A>;
|
|
4657
|
+
static bracket<E, F, R, A>(acquire: IO<E, R>, use: (r: R) => Stream<F, A>, release: (r: R, exit: ReleaseExit<unknown, void>) => IO<never, void>): Stream<E | F, A>;
|
|
4182
4658
|
/**
|
|
4183
4659
|
* Builds a stream by repeatedly running an effectful step over a threaded seed. The step
|
|
4184
4660
|
* returns `Some([element, nextSeed])` to emit and continue, or `None` to end the stream.
|
|
@@ -4227,6 +4703,30 @@ export declare class Stream<E, A> {
|
|
|
4227
4703
|
* const events = Stream.from(queue).map(parse).runForEach(handle);
|
|
4228
4704
|
*/
|
|
4229
4705
|
static from<A>(queue: Queue<A>): Stream<never, A>;
|
|
4706
|
+
/**
|
|
4707
|
+
* Builds a stream that pulls from an async iterable — a Node `Readable`, a `ReadableStream`, a
|
|
4708
|
+
* `Response.body`, an async generator — one value at a time, only when the consumer asks: the
|
|
4709
|
+
* source is never read ahead.
|
|
4710
|
+
*
|
|
4711
|
+
* A `next()` that rejects, or an iterable that cannot give an iterator, fails the stream with
|
|
4712
|
+
* `liftE(error)`, or with the error itself (typed `unknown`) without `liftE`. When the stream
|
|
4713
|
+
* stops before the source ends — the consumer stops early, the run fails or is cancelled — the
|
|
4714
|
+
* iterator's `return()` is called, so the source can release what it holds (a Node `Readable` is
|
|
4715
|
+
* destroyed). It is called without waiting, so a source whose `return()` never settles cannot
|
|
4716
|
+
* hold the stream's end, a `timeout` or a cancellation; the source may still be closing when the
|
|
4717
|
+
* stream ends. A `return()` that fails is ignored. A source that ends by itself is not asked to
|
|
4718
|
+
* return.
|
|
4719
|
+
*
|
|
4720
|
+
* @template A The element type.
|
|
4721
|
+
* @template E The error type `liftE` produces.
|
|
4722
|
+
* @param source The async iterable to read.
|
|
4723
|
+
* @param liftE Turns a rejection of `next()` into an `E`.
|
|
4724
|
+
*
|
|
4725
|
+
* @example
|
|
4726
|
+
* const lines = Stream.fromAsync(readline.createInterface({ input: file }), toReadError);
|
|
4727
|
+
*/
|
|
4728
|
+
static fromAsync<A>(source: AsyncIterable<A>): Stream<unknown, A>;
|
|
4729
|
+
static fromAsync<A, E>(source: AsyncIterable<A>, liftE: (e: unknown) => E): Stream<E, A>;
|
|
4230
4730
|
/**
|
|
4231
4731
|
* Builds a stream from a callback-based source. `register` attaches the listeners and receives
|
|
4232
4732
|
* three synchronous functions — `emit` (a {@link Queue.unsafeOffer}), `end` (a
|
|
@@ -4236,7 +4736,11 @@ export declare class Stream<E, A> {
|
|
|
4236
4736
|
*
|
|
4237
4737
|
* Values are buffered in a bounded {@link Queue} (default capacity 1024, `OverflowStrategy.DropOldest`),
|
|
4238
4738
|
* so a source that outpaces its consumer never grows memory without limit; a `Suspend` queue
|
|
4239
|
-
* makes no sense here because `emit` is synchronous, so it is not offered.
|
|
4739
|
+
* makes no sense here because `emit` is synchronous, so it is not offered. `DropOldest` and
|
|
4740
|
+
* `DropNewest` lose values, so they suit signals where the newest value is enough (a position, a
|
|
4741
|
+
* status). For data that must arrive whole, pass a function as `onOverflow`: when the buffer is
|
|
4742
|
+
* full, the stream fails with the error it returns, after the values already buffered, and
|
|
4743
|
+
* `emit` returns `false` for that value and every later one. A function that throws is a defect.
|
|
4240
4744
|
*
|
|
4241
4745
|
* `register` runs when the stream starts — on the first pull of each **run** (each terminal
|
|
4242
4746
|
* operation), not when `Stream.async` is called — so a value emitted before that point cannot
|
|
@@ -4254,17 +4758,29 @@ export declare class Stream<E, A> {
|
|
|
4254
4758
|
* @template A The element type.
|
|
4255
4759
|
* @template E The error type passed to `fail` (default `never`: a source that cannot fail).
|
|
4256
4760
|
* @param register Attaches listeners; returns the detach effect, if any.
|
|
4257
|
-
* @param options `capacity` (positive integer, default 1024) and `onOverflow
|
|
4761
|
+
* @param options `capacity` (positive integer, default 1024) and `onOverflow`: `OverflowStrategy.DropOldest`
|
|
4762
|
+
* (the default), `OverflowStrategy.DropNewest`, or a function from the capacity to the error to fail with.
|
|
4258
4763
|
*
|
|
4259
4764
|
* @example
|
|
4260
4765
|
* const clicks = Stream.async<MouseEvent>((emit) => {
|
|
4261
4766
|
* button.addEventListener("click", emit);
|
|
4262
4767
|
* return IO.sync(() => button.removeEventListener("click", emit));
|
|
4263
4768
|
* });
|
|
4769
|
+
*
|
|
4770
|
+
* @example
|
|
4771
|
+
* // An upload must arrive whole: fail instead of dropping chunks.
|
|
4772
|
+
* const chunks = Stream.async<Uint8Array, UploadError>(
|
|
4773
|
+
* (emit, end, fail) => {
|
|
4774
|
+
* request.on("data", emit);
|
|
4775
|
+
* request.on("end", end);
|
|
4776
|
+
* request.on("error", (e) => fail(toUploadError(e)));
|
|
4777
|
+
* },
|
|
4778
|
+
* { capacity: 64, onOverflow: () => ({ kind: "uploadTooFast" }) }
|
|
4779
|
+
* );
|
|
4264
4780
|
*/
|
|
4265
4781
|
static async<A, E = never>(register: (emit: (a: A) => boolean, end: () => void, fail: (error: E) => void) => IO<never, void> | void, options?: {
|
|
4266
4782
|
readonly capacity?: number;
|
|
4267
|
-
readonly onOverflow?: Exclude<OverflowStrategy, typeof OverflowStrategy.Suspend
|
|
4783
|
+
readonly onOverflow?: Exclude<OverflowStrategy, typeof OverflowStrategy.Suspend> | ((capacity: number) => E);
|
|
4268
4784
|
}): Stream<E, A>;
|
|
4269
4785
|
/**
|
|
4270
4786
|
* Transforms each emitted element with `f`. Lazy — nothing runs until the stream is consumed.
|
|
@@ -4406,6 +4922,11 @@ export declare class Stream<E, A> {
|
|
|
4406
4922
|
* stream consumed by a fallible `f` is simply `IO<F, void>`).
|
|
4407
4923
|
*/
|
|
4408
4924
|
runForEach<F>(f: (a: A) => IO<F, void>): IO<E | F, void>;
|
|
4925
|
+
/**
|
|
4926
|
+
* Runs `drive` over this stream in a new root scope, and closes the scope with how the run
|
|
4927
|
+
* ended. `drive` pulls until it decides to stop; stopping early is the end of the stream.
|
|
4928
|
+
*/
|
|
4929
|
+
private runScoped;
|
|
4409
4930
|
/**
|
|
4410
4931
|
* Runs the stream purely for its effects, discarding emitted elements.
|
|
4411
4932
|
*/
|